SCRIPT :
IMAGE=$imgvalue;
if [ $imgvalue :=1 ]
then
echo DO=ABC;
elif [ $imgvalue :=2 ]
then
echo DO=ETC;
elif [ $imgvalue :=3 ]
then
echo DO=XYZ;
else
echo "$imgvalue is unsupported";
exit 1;
fi
In the script above, IMAGE=1, IMAGE=2, IMAGE=3 whatever may be the value I have assigned. It's showing only DO=ABC. Other conditions not working. Can anyone explain what's wrong with my script?
If $imgvalue is not an empty string, your first test is a syntax error, so I am assuming it is empty in the tests you are doing. In that case, your first test is equivalent to:
if [ :=1 ]
which is always true because :=1 is not an empty string. You probably meant to write:
if [ "$imgvalue" = 1 ]
Related
I've searched, and searched, and searched... but I just can't figure out why on earth this simple BASH function is failing.
The code:
# Function to quickly disable or enable proxy server, system wide
proxee() {
MODE=$(gsettings get org.gnome.system.proxy mode)
echo $MODE
if [ "$MODE" = "manual" ]
then
gsettings set org.gnome.system.proxy mode 'none'
echo "Proxy Disabled"
elif [ "$MODE" = "none" ]
then
gsettings set org.gnome.system.proxy mode 'manual'
echo "Proxy Enabled"
else
echo "FAIL"
fi
}
Every time I try to run it I get the following output:
'none'
FAIL
I essentially just want to compare the variable I have declared with a string literal.
I am pretty new to bash scripting and I've read over 15 different answers from Stack Overflow (this seems to be a common problem) - but I just can't figure it out!
Any help is much appreciated.
The command gsettings get org.gnome.system.proxy mode returns 'none' including the quote signs (').
Therefore you have to include them into the comparison:
...
elif [ "$MODE" = "'none'" ]
then
...
just change this line:
elif [ "$MODE" = "'none'" ]
string returned to mode is 'none' not none
Enjoy
I'm writing bash scripts that need to work both on Linux and on Mac.
I'm writing a function that will return a directory path depending on which environment I'm in.
Here is the pseudo code:
If I'm on a Mac OS X machine, I need my function to return the path:
/usr/local/share/
Else if I'm on a Linux machine, I need my function to return the path:
/home/share/
Else, you are neither on a Linux or a Mac...sorry.
I'm very new to Bash, so I apologize in advance for the really simple question.
Below is the function I have written. Whether I'm on a Mac or Linux, it always returns
/usr/local/share/
Please take a look and enlighten me with the subtleties of Bash.
function get_path(){
os_type=`uname`
if [ $os_type=="Darwin" ]; then
path="/usr/local/share/"
elif [ $os_type=="Linux" ]; then
path="/home/share/"
else
echo "${os_type} is not supported"
exit 1
fi
echo $path
}
You need spaces around the operator in a test command: [ $os_type == "Darwin" ] instead of [ $os_type=="Darwin" ]. Actually, you should also use = instead of == (the double-equal is a bashism, and will not work in all shells). Also, the function keyword is also nonstandard, you should leave it off. Also, you should double-quote variable references (like "$os_type") just in case they contain spaces or any other funny characters. Finally, echoing an error message ("...not supported") to standard output may confuse whatever's calling the function, because it'll appear where it expected to find a path; redirect it to standard error (>&2) instead. Here's what I get with these cleaned up:
get_path(){
os_type=`uname`
if [ "$os_type" = "Darwin" ]; then
path="/usr/local/share/"
elif [ "$os_type" = "Linux" ]; then
path="/home/share/"
else
echo "${os_type} is not supported" >&2
exit 1
fi
echo "$path"
}
EDIT: My explanation of the difference between assignments and comparisons got too long for a comment, so I'm adding it here. In many languages, there's a standard expression syntax that'll be the same when it's used independently vs. in test. For example, in C a = b does the same thing whether it's alone on a line, or in a context like if ( a = b ). The shell isn't like that -- its syntax and semantics vary wildly depending on the exact context, and it's the context (not the number of equal signs) that determines the meaning. Here are some examples:
a=b by itself is an assignment
a = b by itself will run a as a command, and pass it the arguments "=" and "b".
[ a = b ] runs the [ command (which is a synonym for the test command) with the arguments "a", "=", "b", and "]" -- it ignores the "]", and parses the others as a comparison expression.
[ a=b ] also runs the [ (test) command, but this time after removing the "]" it only sees a single argument, "a=b" -- and when test is given a single argument it returns true if the argument isn't blank, which this one isn't.
bash's builtin version of [ (test) accepts == as a synonym for =, but not all other versions do.
BTW, just to make things more complicated bash also has [[ ]] expressions (like test, but cleaner and more powerful) and (( )) expressions (which are totally different from everything else), and even ( ) (which runs its contents as a command, but in a subshell).
You need to understand what [ means. Originally, this was a synonym for the /bin/test command. These are identical:
if test -z "$foo"
then
echo "String '$foo' is null."
fi
if [ -z "$foo" ]
then
echo "String '$foo' is null."
fi
Now, you can see why spaces are needed for all of the parameters. These are parameters and not merely boolean expressions. In fact, the test manpage is a great place to learn about the various tests. (Note: The test and [ are built in commands to the BASH shell.)
if [ $os_type=="Darwin" ]
then
This should be three parameters:
"$os_type"
= and not ==
"Darwin"
if [ "$os_type" = "Darwin" ] # Three parameters to the [ command
then
If you use single square brackets, you should be in the habit to surround your parameters with quotation marks. Otherwise, you will run into trouble:
foo="The value of FOO"
bar="The value of BAR"
if [ $foo != $bar ] #This won't work
then
...
In the above, the shell will interpolate $foo and $bar with their values before evaluating the expressions. You'll get:
if [ The value of FOO != The value of BAR ]
The [ will look at this and realize that neither The or value are correct parameters, and will complain. Using quotes will prevent this:
if [ "$foo" != "$bar" ] #This will work
then
This becomes:
if [ "The value of FOO" != "The value of BAR" ]
This is why it's highly recommended that you use double square brackets for your tests: [[ ... ]]. The test looks at the parameters before the shell interpolates them:
if [[ $foo = $bar ]] #This will work even without quotation marks
Also, the [[ ... ]] allows for pattern matching:
if [[ $os_type = D* ]] # Single equals is supported
then
path="/usr/local/share/"
elif [[ $os_type == L* ]] # Double equals is also supported
then
path="/home/share/"
else
echo "${os_type} is not supported"
exit 1
fi
This way, if the string is Darwin32 or Darwin64, the if statement still functions. Again, notice that there has to be white spaces around everything because these are parameters to a command (actually, not anymore, but that's the way the shell parses them).
Adding spaces between the arguments for the conditionals fixed the problem.
This works
function get_path(){
os_type=`uname`
if [ $os_type == "Darwin" ]; then
path="/usr/local/share/"
elif [ $os_type == "Linux" ]; then
path="/home/share/"
else
echo "${os_type} is not supported"
exit 1
fi
echo $path
}
I have one function in csh script and in this function I am using one variable which is sourced from one file. But while using script its throwing undefined error for same variable.
I am using Linux.
My Code
function init_remote_commands_to_use
{
# Test if the environment variable SSH_FOR_RCOMMANDS is present in .temip_config file,
# use secured on non secured rcommand depending on the result
if [ "$SSH_FOR_RCOMMANDS" != "" ]
then
if [ "$SSH_FOR_RCOMMANDS" = "ON" ]
then
# Check if the environment variable SSH_PATH is specified in .temip_config file
if [ "$SSH_PATH" != "" ]
then
SH_RCMD=$SSH_PATH
else
SH_RCMD=$SSH_CMD
fi
# Check if a ssh-agent is already running
if [ "$SSH_AGENT_PID" = "" ]
then
#Run ssh-agent for secured RCommands
eval `ssh-agent`
ssh-add
STARTEDBYME=YES
fi
else
if [ "$SSH_FOR_RCOMMANDS" = "OFF" ]
then
SH_RCMD=$RSH_CMD
else
echo "Please set the SSH_FOR_RCOMMANDS value to ON or OFF in the .temip_config file"
exit 1
fi
fi
else
SH_RCMD=$RSH_CMD
fi
}
below is the error:
function: Command not found.
{: Command not found.
SSH_FOR_RCOMMANDS: Undefined variable.
Please anyone suggest what I am missing?
The C Shell csh does not have functions. It does have aliases, but those are harder to write and read. For exmaple, see here: https://unix.stackexchange.com/questions/62032/error-converting-a-bash-function-to-a-csh-alias
It might be a good idea to simply switch to Bash, where your existing code may already be working.
I'm having trouble getting grep to work properly in an if statement. In the following code segment, the if-check always comes up true (i.e. the word is not found), and the program prints NOT FOUND, even though the words are already in ~/.memory.
for (( i=0; i<${#aspellwords[*]}; i++)); do
if [ !$(grep -q "${aspellwords[$i]}" ~/.memory) ]; then
words[$i]="${aspellwords[$i]}"
printf "\nNOT FOUND\n"
fi
done
However, when I test the following code in place of the previous segment:
for (( i=0; i<${#aspellwords[*]}; i++)); do
if grep -q "${aspellwords[$i]}" ~/.memory; then echo FOUND IT; fi
done
It works perfectly fine and finds the word without any issues.
So what's wrong with the first segment of code?
A number of things are wrong with that first snippet.
You don't want [ ... ] if you want to test the return code. Drop those.
[] is not part of the if syntax (as you can see from your second snippet).
[ is a shell built-in and binary on your system. It just exits with a return code. if ...; then tests the return code of ....
$() is command substitution. It replaces itself with the output from the command that was run.
So [ !$(grep ...) ] is actually evaluating [ !output_from_grep ] and [ word ] is interpreted as [ -n word ] which will be true whenever word is non-empty. Given that ! is never non-empty that will always be true.
Simply, as indicated by #thom in his comment (a bit obliquely), add the ! negation to your second snippet with a space between it and grep.
I use for checking the number of params in bash shell as follows:
#! /bin/bash
usage() {
echo "Usage: $0 <you need to specify at least 1 param>"
exit -1
}
[ x = x$1 ] && usage
where, if [ x = x$1 ] condition is not satisfied, execute usage.
Here, my question is, I never really think about the expression [ x = x$1 ] which looks a lot like a condition expression. Is x counted as a literal? and how come can we use = for comparison. Typically should it be something like ==?
Could anybody please fill the void here?
[ x = y ] condition is for comparing strings. (just once =)
x$1 means concatenating two string x and $1.
So, if $1 is empty, x$1 equals x, and [ x = x ] will be true as a result.
[ x = x$1 ] is error prone, don't use it. Do this instead [ "$1" ]
The difference is that if $1 contains a space or other special characters, your script will crash, for example:
$ a='hello world'
$ [ x = x$a ] && echo works
-bash: [: too many arguments
To fix this you could do [ x = x"$1" ], but [ "$1" ] is shorter, so what's the point.
[] expressions are used extensively in shell scripts, I recommend to read help test. The [ is a synonym for the "test" builtin, but the last argument must be a literal ], to match the opening [. In there you will find the explanation of the differences between = and == operators.
Finally, literal text in conditions is evaluated to true if not empty. Some more examples:
[ x ] # true
[ abc ] # true
[ a = a ] # true
[ a = x ] # false
[ '' ] # false
[ b = '' ] # false
Also common gotchas are these:
[ 0 ] # true
[ -n ] # true
[ -blah ] # true
[ false ] # true
These are true, because 0, -n, false or anything being the only argument, they are treated as literal strings, and so the condition evaluates to true.
Use $# to count the number of parameters and use the OR operator instead of the AND so that usage() only gets executed if the first condition fails.
#! /bin/bash
usage() {
echo "Usage: $0 <you need to specify at least 1 param>"
exit -1
}
[ x = $# ] || usage