if statement in .bashrc not working correctly
Solution 1
COLUMNS
variable is set by bash upon receipt of a SIGWINCH.
(see Shell Variables
section in man bash
). It is not set in your script because this is not an environment variable. See yourself:
$ export COLUMNS=$COLUMNS
$ ./your-script.sh
Now it works. You need to retrieve value of COLUMNS
in your script. You can use tput
for example:
$ tput cols
186
Solution 2
COLUMNS
is not set somehow in .bashrc
.
Just get the columns via tput cols
like this:
dp_smaller_than=80
if [ $(tput cols) -lt $dp_smaller_than ]
then
PROMPT_COMMAND="degr_prompt"
else
PROMPT_COMMAND="full_prompt"
fi
Related videos on Youtube
psimon
I'm a high school student, interested mainly in GNU/Linux administration and programming. I mostly use BASH, but I learn C and C++ as well. I tweak my home network for security and performance. My latest project is setting up virtualization to deploy a server on an AMD PC. I'm also a homebrewer radio amateur and a mountain bike lover. I develop utilities for JackOS, a Debian derivate distribution. It's in an early stage of development, but you can find the first programs on my GitHub.
Updated on September 18, 2022Comments
-
psimon over 1 year
I set up
.bashrc
to show a long prompt if the terminal is at least 80 characters wide. Otherwise it shows a degraded, smaller prompt.I use an
if
statement to achieve this:dp_smaller_than=80 if [ $COLUMNS -lt $dp_smaller_than ] then PROMPT_COMMAND="degr_prompt" else PROMPT_COMMAND="full_prompt" fi
It only works correctly if I put a
sleep 0
or other command before this statement, otherwise it shows the following error:[: -lt: unary operator expected
Note: I have the
degr_prompt
andfull_prompt
functions defined in the beginning of the file.-
polym almost 10 yearscan you provide the statement, which sets
COLUMNS
? -
psimon almost 10 years@polym, it is set automatically.
-
-
psimon almost 10 yearsYou're right. Strange,
$COLUMNS
only get set if a command gets executed. I tested it withecho $COLUMNS
. -
polym almost 10 years+1 because of
SIGWINCH
info. -
phemmer almost 10 years@psimon
man bash
:checkwinsize - If set, bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
. So if you've gotcheckwinsize
set, you just need to execute a command (a simple:
would suffice). -
psimon almost 10 years@Patrick it seems that not all commands work for this.
sleep
,echo
,printf
work, butalias
,shopt
,[
or setting variables don't (I have these before theif
statement in.bashrc
). Is it in connection with interactivity?