Bash script command result inside other variable to define prompt - bash

I would like to define a prompt which will indicate with colors whether the command executed properly and whether the command was found. As for now I have something like this but I does not work properly.
PS1="\`COMMAND_RESULT=\$\?;
if [ $COMMAND_RESULT -eq 127 ]; then echo \[\e[33m\] ---=== Command not found ===--- ;
elif [ $COMMAND_RESULT -ne 0 ]; then echo \[\e[33m\]---=== \[\e[31m\]Oh noes, bad command \[\e[33m\]==---;
fi\`
\n\[\e[0;37m\][\[\e[1;31m\]\#\[\e[0;37m\]]
\[\e[0;32m\]\u\[\033[1;33m\]#\[\033[0;32m\]\h
As for now I get this error on bash start :
-bash: [: -eq: unary operator expected
-bash: [: -ne: unary operator expected

Don't pollute your PS1 with functions. You should use the special PROMPT_COMMAND variable to do this. The value of PROMPT_COMMAND is executed as a command prior to issuing each primary prompt.
Here is an example:
_check_command(){
local COMMAND_RESULT=$?
if [ $COMMAND_RESULT -eq 127 ]
then
echo -e "\e[1;33m---=== Command not found ===---\e[m"
elif [ $COMMAND_RESULT -ne 0 ]
then
echo -e "\e[1;31m---=== Oh noes, bad command ===---\e[m"
fi
}
PROMPT_COMMAND='_check_command'
PS1="\[\e[0;37m\][\[\e[1;31m\]\#\[\e[0;37m\]] \[\e[0;32m\]\u\[\033[1;33m\]#\[\033[0;32m\]\h "
There are many bash prompts you can find online to guide you. Here is one good example.

You probably should not escape $? as \$\?. Looks like it gets interpreted literally.
Also you can check out the Arch Wiki article that shows how to implement something similar to what you want. Look at this line:
PS1="$(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h'; else echo '\[\033[01;32m\]\u#\h'; fi)\[\033[01;34m\] \w \$([[ \$? != 0 ]] && echo \"\[\033[01;31m\]:(\[\033[01;34m\] \")\$\[\033[00m\] "
especially this part:
([[ \$? != 0 ]] && echo \"\[\033[01;31m\]:(\[\033[01;34m\] \")

Related

convert read string to integer in bash

I'm trying to read from user and then do the following.
read framechoice
if [ $framechoice -gt 100 ]; then
if [ $framechoice -lt 0 ]; then
framechoice=101
fi
fi
It gives me the following error.
[: -gt: unary operator expected
Can anyone tell me where I am going wrong.
This happens if you don't input anything:
$ cat myscript
read framechoice
if [ $framechoice -gt 100 ]; then
if [ $framechoice -lt 0 ]; then
framechoice=101
fi
fi
$ bash myscript
<enter>
myscript: line 2: [: -gt: unary operator expected
Try instead to actually enter something:
$ bash myscript
42<enter>
The script then exits with success.
Your program needs to cope with empty input. This is most easily achieved by properly quoting the variable; then
if [ "$framechoice" -gt 100 ]; then
evaluates to [ "" -gt 100 ] which is no longer is a syntax error; however, instead, it throws the warning integer expression expected.
Even better, maybe filter the input so that you do not attempt numeric comparisons before making sure the input is numeric.

Getting error in if clause in shell script inside jenkins job

I am having shell script like this
while read -r LINE || [[ -n $LINE ]]; do
noStudent="false"
LINE=$(echo "$LINE" | tr '[:upper:]' '[:lower:]')
if [ $LINE == "myname" ]
then
noStudent="true"
fi
if [ $noStudent == "true" ]
then
#DO SOME STUFF
fi
done < Teachers
But I am getting error on each line when files is read :
+ [ yourname == myname ]
/tmp/hudson433507028658734743.sh: 20: [: yourname: unexpected operator
+ [ false == true ]
/tmp/hudson433507028658734743.sh: 26: [: false: unexpected operator
What can be the reason for it ? Please help. Am not able to figure out.
Your script isn't actually being executed by bash, but by some other shell linked to by /bin/sh (likely dash, see below). The POSIX standard does not recognize == as a valid operator with the [ command; you need to use = instead.
Using dash, for example, this can be reproduced with
$ [ foo == foo ] && echo same
dash: 5: [: foo: unexpected operator
$ [ foo = foo ] && echo same
same
$
You will almost certainly use [ because you are concerned about portability, in which case you must also use =. If you aren't concerned about portability, and your shell allows == inside [, you can almost certainly (and probably should) use [[ instead.

Mac Bash - doesn't recognize if[$#=0]

It's been a while since I've scripted in bash so I made a small script to test things out. This is my script (the quoted text is some Dutch, doesnt really matter):
#isingelogd
if[$#=0]
then
echo "Geef user-id's op!" 1>$2 ; exit 1
fi
for uid in $*
do
if who|grep $uid >dev/null
then
echo $uid is ingelogd
else
echo $uid is niet ingelogd
fi
done
If I try to run it it tells me the following:
bash-3.2$ ./isingelogd
./isingelogd
./isingelogd: line 3: if[0=0]: command not found
./isingelogd: line 4: syntax error near unexpected token `then'
./isingelogd: line 4: `then'
If I check my version with bash -v I'm running 3.2 which I thought supported square brackets.
Has someone had a similar problem and found solution?
Look at your errors:
bash-3.2$ ./isingelogd
./isingelogd
./isingelogd: line 3: if[0=0]: command not found
./isingelogd: line 4: syntax error near unexpected token then'
./isingelogd: line 4:then'
See that command not found? you have an error in your script.
The [..] are actual commands, and like all commands, they need to be separated by white spaces. The = is a parameter to the [ command and also needs to be surrounded by white space. Change line #3 to this:
if [ $# -eq 0 ]
Since $# and 0 are numeric, you should use -eq which compares to numbers and not = which compares strings.
Try these commands:
$ ls -li /bin/test
$ ls -li /bin/[
You'll see they have the same inode number. They're links. (Yes, the [ and test are builtins into the shell, but they are linked builtin commands).
$ man test
will give you all of the various tests that [ can do. Again, note the difference between -eq vs. = and -gt vs. >.
Note the following:
if [ 54 > 123 ]
then
echo "54 is greater than 123"
fi
This will print out "54 is greater than 123". This won't:
if [ 54 -gt 123 ]
then
echo "54 is greater than 123"
fi
a.bash works for me in Mac. Content of a.bash is the following :
#!/bin/bash
if [ $# == 0 ]; then
echo "Usage da da do"
fi
export A=$1
echo $A
then execute with the following :
\# ] ./a.bash
Usage da da do

"" on $1, why does bash behave like this?

if a script has
if [ $1 == "-?" ]; then #line 4
echo "usage: ...."
fi
when the script get runs without any parameter, it will complain that
./script.sh: line 4: [: ==: unary operator expected
but if instead
if [ "$1" == "-?" ]; then #line 4
echo "usage: ...."
fi
then everything's fine
why is that?
thanks
If the first argument is missing or empty, your first script evaluates to:
if [ == "-?" ] ; then
... which is a syntax error. As you noticed, to prevent that you need to make use of "", then it evaluates to:
if [ "" == "-?" ] ; then
AFAIK this is due to the way the original Bourne shell was working. You should make it a habit of enclosing variables in "" to also work correctly with arguments that have spaces in it. For example, if you would call your script like this:
./myScript "first argument has spaces"
Then your first script would evaluate to:
if [ first argument has spaces == "-?" ] ; then
which is also a syntax error. Also things like rm $1 will not do what you want if you pass filenames with spaces. Do rm "$1" instead.
Because [ replaces the values before executing. [[ doesn't, so will work as expected.

BASH: read in while loop

while [ $done = 0 ]
do
echo -n "Would you like to create one? [y/n]: "
read answer
if [ "$(answer)" == "y" ] || [ "$(answer)" == "Y" ]; then
mkdir ./fsm_$newVersion/trace
echo "Created trace folder in build $newVersion"
$done=1
elif [ "$(answer)" == "n" ] || [ "$(answer)" == "N" ]; then
$done=2
else
echo "Not a valid answer"
fi
done
Ok so I have this simple bashscript above that simply just tries to get input from a user and validate it. However I keep getting this error
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
Which I have no idea why because "answer" is nowhere near line 1. So I ran into this article
Which makes sense since it's referring to line 1 and can't find answer. So it seems to be starting a new subshell. However I didn't really understand the solution and can't see how I would apply it to my case. I just wanna get this to work.
$(answer) doesn't substitute the value of the variable answer. It executes answer as a command, and substitutes the output of that command. You want ${answer} everywhere you have $(answer). In this case you can get away with bare $answer too, but overuse of ${...} is good paranoia.
(Are you perhaps used to writing Makefiles? $(...) and ${...} are the same in Makefiles, but the shell is different.)
By the way, you have some other bugs:
In shell, you do not put a dollar sign on the variable name on the left hand side of an assignment. You need to change $done=1 to just done=1 and similarly for $done=2.
You are not being paranoid enough about your variable substitutions. Unless you know for a fact that it does the wrong thing in some specific case, you should always wrap all variable substitutions in double quotes. This affects both the mkdir command and the condition on the while loop.
You are not being paranoid enough about arguments to test (aka [). You need to prefix both sides of an equality test with x so that they cannot be misinterpreted as switches.
== is not portable shell, use = instead (there is no difference in bash, but many non-bash shells do not support == at all).
Put it all together and this is what your script should look like:
while [ "x${done}" = x0 ]; do
echo -n "Would you like to create one? [y/n]: "
read answer
if [ "x${answer}" = xy ] || [ "x${answer}" = xY ]; then
mkdir "./fsm_${newVersion}/trace"
echo "Created trace folder in build $newVersion"
done=1
elif [ "x${answer}" = xn ] || [ "x${answer}" = xN ]; then
done=2
else
echo "Not a valid answer"
fi
done
Which I have no idea why because
"answer" is nowhere near line 1. So I
ran into this article
That's not your problem here.
I ran the script and did not get the error you got. I did receive the error:
./test.sh: line 1: [: -eq: unary operator expected
when I tried to compile though. Defining done fixed this. The following script should work...
#!/bin/bash
done=0
while [ $done -eq 0 ]
do
echo -n "Would you like to create one? [y/n]: "
read answer
if [[ "$(answer)" == "y" || "$(answer)" == "Y" ]]; then
mkdir ./fsm_${newVersion}/trace
echo "Created trace folder in build $newVersion"
$done=1
elif [[ "$(answer)" == "n" || "$(answer)" == "N" ]]; then
$done=2
else
echo "Not a valid answer"
fi
done
...note you were doing string comparisons on your done variable, which you apparently intended to be numeric. It's generally bad form to do string comparison on a numeric type variable, though it will work. Use -eq (arithmetic comparison operator) instead. (Also note that if you kept that test, your string equality would be inconsistent... you had "=" in one spot and "==" in another spot... nitpicking here, but it's helpful to be consistent).
Also, I suggest double brackets for your compound conditionals as they will be more readable if you have longer ones. e.g.
if [[($var1 -eq 0 && $var2 -eq 1) || ($var1 -eq 1 && $var2 -eq 0)]]; then
Just a matter of preference as you only have two conditions, but could be useful in the future.
Also you were missing braces '{' '}' around your newVersion variable.
Finally, I'd suggest putting the line #!/bin/bash on the top of your script. Otherwise its up to your environment to determine what to do with your script, which is a bad idea.

Resources