Question

I need to check creating and changing dir for the new directory and print error ion fail someone from them like the following:

[ mkdir tmp && cd tmp ] || echo "error"

But I'm getting the following error:

[: missing `]'
Was it helpful?

Solution

&& is not allowed inside the brackets of a test command, so the missing ] is the one that bash believes should be between tmp and &&.

A correct form of your command would be

mkdir tmp && cd temp || echo "error"

If mkdir fails, (or cd fails after mkdir succeeds), then execute the echo. No test/[ command is needed.

OTHER TIPS

[ -d tmp ] || mkdir tmp

Is probably what you are looking for. This checks for the existence of the directory then creates it if it does not exist.

[ -d tmp ] || mkdir tmp || echo "failure"

displays a message if the mkdir fails.

or the more verbose but clearer version:

if [ ! -d temp ] # if there is no directory
then
     mkdir temp
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top