Jump to content

HowTo: Use Bash Parameter Substitution Like A Pro


securitybreach

Recommended Posts

securitybreach

The $ character is used for parameter expansion, and command substitution. You can use it for manipulating and/or expanding variables on demands without using external commands such as sed or awk.

 

#1: Getting Up Default Shell Variables Value

 

The syntax is as follows:

${parameter:-defaultValue}
var=${parameter:-defaultValue}

 

If parameter not set, use defaultValue. In this example, your shell script takes arguments supplied on the command line. You'd like to provide default value so that the most common value can be used without needing to type them every time. If variable $1 is not set or passed, use root as default value for u:

u=${1:-root}

 

Consider the following example:

#!/bin/bash
_jail_dir="${1:-/home/phpcgi}"
echo "Setting php-cgi at ${_jail_dir}..."
# rest of the script ...

 

You can now run this script as follows:

./script.sh /jail # <--- set php jail at /jail dir
./script.sh /home/httpd/jail # <---- set php jail at /home/httpd/jail dir
./script.sh # <--- set php jail dir at /home/phpcgi (default)

 

Here is another handy example:

_mkdir(){
local d="$1" # get dir name
local p=${2:-0755} # get permission, set default to 0755
[ $# -eq 0 ] && { echo "$0: dirname"; return; }
[ ! -d "$d" ] && mkdir -m $p -p "$d"
}

 

Use this substitution for creating failsafe functions and providing missing command line arguments in scripts.......

http://www.cyberciti...titution-2.html

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...