Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have this code:

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

where $i is something like this


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?

share|improve this question
Please, do not cross post: askubuntu.com/questions/89561/impossible-to-compare-string – enzotib Dec 21 '11 at 18:16
up vote 2 down vote accepted

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%/}
$ i="app4/"; echo ${i%/}


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

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

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

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

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.