Create a bash function with parameters to use as an alias
I have realised that my folders follow a specific structure and wanted to access them with cd faster, so I tried to make this alias / function that would behave like this:
cdc glm 03
would be equivalent to
cd ~/Documents/7glm/week03
And I tried defining such function (in ./bashrc) but it does not work. Running it does not paste the parameters:
cd ~/Documents/7/week
The function:
cdc () {
if [ $# -lt 2 "$1" ]; then
echo "Usage: cdc <folder_name> <folder_number>"
else
folder_name="$1"
folder_number="$2"
cd ~/Documents/7"$foldername"/week"$foldernumber"
fi
}
What am I doing wrong (very new to bash)?
Thanks!
You’ll need to take care of two issues:
-
The first being too many arguments inside the test brackets
[ ... ]
around the-lt
operator … Namely2 "$1"
. -
The second being inconsistent parameter naming in setting and expansion … e.g.
folder_name
and"$foldername"
.
… and your function should, accordingly, be:
cdc () {
if [ $# -lt 2 ]; then
echo "Usage: cdc <folder_name> <folder_number>"
else
folder_name="$1"
folder_number="$2"
cd ~/Documents/7"$folder_name"/week"$folder_number"
fi
}