2

I have this code:

if [ $i | sed -e "s/^.*\(.\)$/\1/" = "/" ]
then
    echo "folder"
else
    echo "file"
fi

where $i is something like this

app4/

The code above should get the last char of the string and check if it is a slash (/), but it tells me:

./str: line 12: =app4/: File or directory doesn't exist

How can I solve this?

1

2 Answers 2

2

You can substitute the value of $i in to see the exact command you're trying to run:

app4/ | sed -e "s/^.*\(.\)$/\1/"

This doesn't work because app4/ isn't a command. You're trying to pipe app4/ into sed, so you need to use something that outputs app4/:

echo app4/ | sed -e "s/^.*\(.\)$/\1/"

This works, but you don't really need to use sed for this; bash has quite a few string manipulation tools. For example, ${i#} will give you the length of $i, and ${i:j} will give you a substring starting at j, so ${i:$((${i#}-1))} will give you the last character.

The easiest way to do what you're trying is probably with ${i%/}. This will return $i, but will strip off a / from the end if there is one:

$ i="app4"; echo ${i%/}
app4
$ i="app4/"; echo ${i%/}
app4

Thus:

if [ "${i%/}" = "$i" ]
then
    echo "file"
else
    echo "folder"
fi

However, if all you really want is to know if $i is a valid directory, you can just use:

if [ -d "$i" ]
3
  • perfect! i can't use -d because i need to create that directory Dec 21, 2011 at 20:44
  • Then create the dir if it is missing with: if [ ! -d $i ]; then mkdir -p $i; fi
    – Johan
    Dec 22, 2011 at 6:39
  • 1
    @Johan: Or just mkdir -p $i, which does nothing if it's already a directory. Jan 11, 2012 at 1:17
1

The easiest way to check if the variable ends in / is:

[[ $i = */ ]]

..although as Johan said, you can just check whether it exists and create it if not. That should however be quoted properly:

if [[ ! -d $i ]]; then
    mkdir -p "$i" || exit 1
fi

We don't need to quote expansions inside [[ .. ]] which, along with its greater utility and speed, makes it much nicer to use; we definitely need to quote the parameter to mkdir.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .