Quote:
Originally Posted by takayama
i want to overwrite that default value with the new one from $2.
|
This is basic
Bash parameter expansion. Use
If you have the default value in say variable
default2, then use
Quote:
Originally Posted by takayama
The second one is that i want to use the ipaddress my eth0 device having as a variable.
|
Code:
ip0=`ifconfig eth0`
ip0="${ip0##*inet addr:}"
ip0="${ip0%% *}"
The first line runs
ifconfig to get the description block for eth0. The second line removes everything before the IP address. The last line removes everything after the IP address. Therefore you end with just the IP address for eth0.
Quote:
Originally Posted by takayama
Also i would like to have script that i can use with "multilevel" arguments, like if the script is named sysinfo, i can call it like this.
|
Use a
while loop to process any command line parameters left. Use
shift N to move parameters
N steps left, removing the
N first parameters. Here is an example skeleton:
Code:
#!/bin/bash
Usage () {
exec >&2
echo ""
echo "Usage: $0 [ -h | --help ]"
echo " $0 hdd cmd device"
echo " $0 cpu cmd"
echo ""
exit ${1:-1}
}
# If no parameters, output usage.
[ $# -lt 1 ] && Usage 0
# Loop for as long as there are parameters left.
while [ $# -gt 0 ]; do
# Next parameter is the "command". Remove it from the list.
cmd="$1"
shift 1
# Process the command.
case "$cmd" in
hdd)
# hdd cmd dev
if [ $# -lt 1 ]; then
echo "hdd: No command or device specified." >&2
exit 1
fi
if [ $# -lt 2 ]; then
echo "hdd: No device specified." >&2
exit 1
fi
cmd="$1"
dev="$2"
shift 2
# TODO: act on "hdd $cmd $dev".
echo "HDD: cmd=$cmd, dev=$dev"
;;
cpu)
# cpu cmd
if [ $# -lt 1 ]; then
echo "cpu: No command specified." >&2
exit 1
fi
cmd="$1"
shift 1
# TODO: act on "cpu $cmd".
echo "CPU: cmd=$cmd"
;;
-h|--help|help)
Usage 0
;;
*)
echo "$1: Unknown command." >&2
exit 1
;;
esac
done
To simplify each subcommand, you could put each one in their own function. Since the positional parameters
$1,
$2, and so on are the parameters for the function, you'll need to save the script arguments to a separate array, and have the functions modify that array directly. In the above script, you'd have to add the array initialization, for example
Code:
arg=("" "$@") ; unset arg[0]
before anything else in the script (say, on the second line), and then do these replacements:
Code:
$1 -> ${arg[1]}
$2 -> ${arg[2]}
$# -> ${#arg[@]}
$@ -> ${arg[@]}
shift 1 -> unset arg[1] ; arg=("" "${arg[@]}") ; unset arg[0]
shift 2 -> unset arg[1] arg[2] ; arg=("" "${arg[@]}") ; unset arg[0]
Unlike positional parameters, you can then modify the script parameter list anywhere, even inside a function.
Hope this helps.