Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
can you provide the statement, which sets COLUMNS? –  polym Jun 24 at 14:09
    
@polym, it is set automatically. –  psimon Jun 24 at 14:11

2 Answers 2

up vote 8 down vote accepted

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
share|improve this answer
    
+1 because of SIGWINCH info. –  polym Jun 24 at 14:53

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|improve this answer
1  
You're right. Strange, $COLUMNS only get set if a command gets executed. I tested it with echo $COLUMNS. –  psimon Jun 24 at 14:30
    
@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). –  Patrick Jun 24 at 15:27
    
@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? –  psimon Jun 24 at 15:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.