Shell expansion

One of annoying things about Linux shell is the strange shell syntax.

Bash brace expansion

==================


The following code cp menu.lst tom menu.lst.bak:


cp /boot/grub/menu.lst{,.bak}

/boot/grub/menu.lst{,.bak} will be expanded to the orignal pathname and a new pathname suffixed with .bak. Run "echo /boot/grub/menu.lst{,.bak}" to see the effect.

For a detailed explanation, refer to
http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion.

Tilde Expansion

=============

The following code sets HADOOP_CONF_DIR to $HADOOP_HOME/conf if HADOOP_CONF_DIR has not been set.

HADOOP_CONF_DIR="${HADOOP_CONF_DIR:-$HADOOP_HOME/conf}"

It is the ${parameter:−word} pattern.

The following code uses ${parameter#word} and ${parameter%word} patterns.

#!/bin/bash

for i in $(cut -f 1,3 -d: /etc/passwd) ; do
    echo "${i#*:}" "=" "${i%:*}"
done

Refer to 

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

Arrays

======

array=(one two three four)

for i in "${array[@]}"; do
echo $i
done

echo "${array[*]}"
echo "${array[@]}"
echo "${array[0]}"
echo "${#array[0]}"
echo "${#array[@]}"
 

猜你喜欢

转载自yaojingguo.iteye.com/blog/761637