Reputation: 7097
Why does this fail?
~$ su - -c "k=0; if ls | grep -q ^Desktop; then k=1; fi; if [ $k == 1 ]; then echo 1; fi"
Password:
-bash: line 0: [: ==: unary operator expected
It works without the su - -c
part.
Update
It was a simplified example, what I really wanted was
ssh -t $host 'su - -c "k=0; if yum check-updates | grep -q ^kernel-; then k=1; fi; yum -y update; if [ \$k == 1 ]; then reboot; fi"'
which now works thanks to the help I got here.
Upvotes: 1
Views: 93
Reputation: 46833
That's because your shell will do a variable expansion (because you're using double quotes), and very likely k
expands to nothing since it's not set. Please consider instead:
su - -c "k=0; if ls | grep -q ^Desktop; then k=1; fi; if [ \$k == 1 ]; then echo 1; fi"
(with escaped dollar) or:
su - -c 'k=0; if ls | grep -q ^Desktop; then k=1; fi; if [ $k == 1 ]; then echo 1; fi'
with single quotes that prevent variable expansion.
And by the way, it's very bad to parse the output of ls
! it seems your problem is to determine whether a file or directory with name starting with Desktop
exists. Using a little bit of heuristic, I guess you really mean whether there exists a directory the name of which is exactly Desktop. In this case:
if [[ -d Desktop ]]; then k=1; fi
will be much better. If not in Bash (or in Bash but want to avoid Bashisms):
if [ -d Desktop ]; then k=1; fi
Upvotes: 7