I'm trying to wrap my head around the command `mkdir ${1:-aa}`. It seems to work, and if I replace `1` with another number, it still does what I expect. I also noticed that `mkdir ${a:-a}` appears to create a directory named `1`, but `mkdir ${b:-b}` just creates a directory called `b`. I'm curious about how all this works. Any insights would be greatly appreciated as I'm eager to learn more!
5 Answers
Just a quick explanation: The `$1` is the first argument passed to a script. If you run a script called `md` with `md foobar`, it will create a directory called "foobar". If there's no argument, `$1` is unset which could lead to trying to create a directory with an empty name, so it often fails. Using `${name-value}` provides a default value, and adding a colon prevents empty strings. So `${1:-aa}` takes value from the first argument or uses "aa" if not provided!
If you want more context, check out the Bash Guide on parameter expansion which has all these details. It explains that if you don't provide an argument, it defaults to an empty string. This can mess things up unless you use the syntax `${name:-value}` which provides a way to use an alternative if the variable isn't set.
The syntax you used is pretty powerful! Basically, when you're calling a script, the first argument is assigned to `$1`. Using `${1:-aa}` sets a fallback to "aa" if nothing is passed. It's a great way to avoid errors and ensure a directory is created even if no arguments were given!
The command `mkdir ${1:-aa}` tries to use the first command-line argument. If you don’t provide any argument, it creates a folder called "aa". For the `mkdir ${a:-a}` it likely means you set variable `a` to `1` at some point, which is why it creates a folder named `1`. When you run `mkdir ${b:-b}`, since `b` is not set, it defaults to creating `b`. Also, remember to quote your variables like `mkdir "${1:-aa}"` to handle spaces correctly!
The `${1:-aa}` syntax means that if the first argument ($1) doesn't exist, it will use "aa" instead. You can check out the Bash manual section on parameter expansion for more details. If you want to see it live, open a terminal and type `man bash`, then search for ":-" or ":="! It's pretty handy!
Thanks for the info! That makes more sense now.
How do you search inside the `man` pages? I never knew that was possible!