I have a bash script I am trying to run through directories to the end of the line, for example if I have 4 directories in a row it will go down /d1/d2/d3/d4 until it finds files or other directories. If d3 has a file, it will stop there. I was doing this by counting the lines ls prints to a file and if there's 1 directory use that name in a cd command.
My file is:
`
#!/bin/bash
COUNTFILE="/home/username/fake.txt"
ITEMCOUNT=$(ls | wc -l)
echo "ITEMCOUNT" $ITEMCOUNT
echo $*
ONE="1"
echo "one" $ONE
if [["$ITEMCOUNT" -eq "$ONE"]];
then
DIRCOUNT=$(find . -maxdepth 1 -type d | wc -l)
echo "dircount" $DIRCOUNT
else
DIRCOUNT="0"
fi
if [$DIRCOUNT == "1"]; then
ls > $COUNTFILE
PATH=$(head -1 $COUNTFILE)
cd ./$PATH
fi
`
As is I get
pipetester.sh: line 15: [[1: command not found
pipetester.sh: line 2
4: [0: command not found
I checked syntax for 2 hours, but it seems to be complaining about my "if" lines, why?
Put spaces around command names like [[
and [
.
For example:
if [[ "$ITEMCOUNT" -eq "$ONE" ]]
then
or, if you like semicolons:
if [[ "$ITEMCOUNT" -eq "$ONE" ]]; then
And:
if [ $DIRCOUNT == "1" ]; then
or (better use of quotes):
if [ "$DIRCOUNT" == "1" ]; then # Or just 1 (no quotes around it)
Because these are commands, you need spaces around the components of the expression too (as you have them already). Don't skimp on spaces in shell scripts (but also don't use them where they are not allowed, such as around the =
in a variable assignment).
Note that both the [[
command and the ==
operator for [
are Bash extensions compared to the POSIX shell.
You need to put spaces around the [[
and ]]
tokens, [[
is an actual command:
if [[ "$ITEMCOUNT" -eq "$ONE" ]];
The way you have it now is little different to expecting ls-al
(without a space preceding the -
) to give you a full directory listing.
The complaint about the [[1
command is because $ITEMCOUNT
is set to 1 and is being combined with the [[
text:
pax$ xyzzy=1
pax$ if [[$xyzzy == 1]]; then echo yes; fi
-bash: [[1: command not found
pax$ if [[ $xyzzy == 1 ]]; then echo yes; fi
yes
You also need to do this for [
and ]
as well, for the same reason.