if statement in .bashrc not working correctly

5,302

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
Share:
5,302

Related videos on Youtube

psimon
Author by

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, 2022

Comments

  • psimon
    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 and full_prompt functions defined in the beginning of the file.

    • polym
      polym almost 10 years
      can you provide the statement, which sets COLUMNS?
    • psimon
      psimon almost 10 years
      @polym, it is set automatically.
  • psimon
    psimon almost 10 years
    You're right. Strange, $COLUMNS only get set if a command gets executed. I tested it with echo $COLUMNS.
  • polym
    polym almost 10 years
    +1 because of SIGWINCH info.
  • phemmer
    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 got checkwinsize set, you just need to execute a command (a simple : would suffice).
  • psimon
    psimon almost 10 years
    @Patrick it seems that not all commands work for this. sleep, echo, printf work, but alias, shopt, [ or setting variables don't (I have these before the if statement in .bashrc). Is it in connection with interactivity?