String comparison in single brackets in zsh
29,556
Solution 1
There are various issues here. First, ==
is not standard, the POSIX way is =
. Same goes for the -o
. This one will work on both bash and zsh:
for f in ~/*;
do
if [ "$f" = '/home/sk/.' ] || [ "$f" = '/home/sk/..' ]; then
true
else
echo "$f"
fi
done
Note that your if
is unneeded, dotfiles are ignored by default in both bash and zsh. You can simply write:
for f in ~/*; do echo "$f"; done
Or even
printf "%s\n" ~/*
Solution 2
Try:
if [ "$f" = '/home/sk/.' ] || [ "$f" = '/home/sk/..' ]
Related videos on Youtube
Author by
Admin
Updated on September 18, 2022Comments
-
Admin almost 2 years
Bash code to print all folders:
for f in ~/*; do if [ $f == '/home/sk/.' -o $f == '/home/sk/..' ]; then true else echo "$f" fi done
It works on bash. When i ran the code on z shell, it threw error:
= not found
Then I converted
[
into[[
,]
into]]
to avoid this error in z shell and ran it on z shell. It threw next error:condition expected: $f
With
[[
and]]
, bash also throws error as:syntax error in conditional expression syntax error near `-o'
Is there a POSIX standard to do string comparison in shell, that works across shells?
-
terdon about 9 yearsAre there any shells that will include dotfiles when expanding
*
? Neither bash nor zsh do. -
Janis about 9 years@terdon; Not any shell that I know of. - Note that I was addressing just the OP's question in my answer, not any optimization beyond.
-
terdon about 9 yearsI understood that, hence my upvote. Since I'm pretty sure your knowledge of the shell ecosystem is far more extensive than my own, I thought I'd ask just in case :)
-
Admin about 9 yearshi terdon, i have set
shopt
fordotglob
set asoff
. But still i am getting.
and..
inside the for loop in bash. so, i chose to do this fix...ls -a
also lists the two entries -.
and..
-
terdon about 9 years@MadhavanKumar if you are seeing dotfiles, then
dotglob
is set somehow. They won't appear otherwise. -
Gilles 'SO- stop being evil' about 9 years@terdon Neither does by default, but ksh, bash and zsh can be configured to include dot files.
-
Gilles 'SO- stop being evil' about 9 years@MadhavanKumar In bash, set
GLOBIGNORE=.:..
to skip.
and..