I'm trying to create a directory and cd into it:
In ~/.bashrc:
function abc() { appname=$1 appdir="$HOME/code/$appname" if [ mkdir $appdir -a cd $appdir ]; then echo Success else echo Failed to create and switch directory fi
}When I reload bashrc (. ~/.bashrc) I get the error:
bash: [: too many arguments
Failed to create and switch directoryHow do I fix this? And what does [: in the error mean?
Ps. Could someone direct me to a "non-cryptic" bash scripting tutorial?
22 Answers
The main error in your script is that the [ command, equivalent to test command, is used to test conditions, like string comparison, existence of files, and so on.
To test the exit status of processes you have to use if without [, so your script could be
if mkdir "$appdir" && cd "$appdir"; then echo "Success"
else echo "Failed to create and switch directory"
fiThis is explained in Bash Pitfalls: 9. if [grep foo myfile.
I suggest you go through GrayCat Bash Guide to understand bash.
2A prototype could be:
- Create a file in your desktop:
touch newDirectory.sh - Make file executable:
chmod +x newDirectory.sh - To call the script from a terminal in the desktop :
./newDirectory.sh anyName
/
#!/bin/bash
function abc() { appname=${1} appdir="$HOME/Desktop/$appname" if (( mkdir "${appdir}" )) ; then cd "${appdir}" echo "Success" else echo "Failed to create and switch directory" fi
}
abc ${1}Little recommendation: if you are new, do not mess with .bashrc :)