shell - JasonWayne/personal-wiki GitHub Wiki

Shell Self Reference manual

Great Tutorial

eval

[Shell脚本eval、``和$()、[[和、 $(( ))和(())、${}
Also see this stackoverflow link

$@, $?, $0等的意义

http://c.biancheng.net/cpp/view/2739.html

Difference between $* and $@

$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(" ")包含时,都以"$1" "$2" … "$n" 的形式输出所有参数。

但是当它们被双引号(" ")包含时,"$*" 会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;"$@" 会将各个参数分开,以"$1" "$2" … "$n" 的形式输出所有参数。原始链接

./test.sh "a" "b" "c" "d"

print each param from "$*"
a b c d
print each param from "$@"
a
b
c
d

Test Command

https://www.computerhope.com/unix/test.htm http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

if中 [[和]的区别

简单的说[[有更多功能,不会意外interpret一些字符串,但兼容性更差(bash支持,sh不支持)。<[[中解释为小于,在[中解释为输入流。 更多可以查看这个问答

Base example

Advanced example

2>&1

这里突然看到这样一行奇怪的语句:

$javac MyFirstJavaProgram.java 2>&1

StackOverflow上给出了答案:

File descriptor 1 is the standard output (stdout). File descriptor 2 is the standard error (stderr). Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows is a file descriptor and not a filename. So the construct becomes: 2>&1.

如何处理输入的参数

http://www.shelldorado.com/goodcoding/cmdargs.html#flagnames http://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash

结合上面两个连接上的代码,我自己写的:

#!/bin/sh

usage_str="usage: $0 -d 2015-08-01 [-h 02]"

if [ $# -lt 1 ]; then
	echo $usage_str
	exit 1
fi

while [ "$1" != "" ]; do
	case $1 in
		-d | --date )
			shift
			date=$1
			;;
		-h )
			shift
			hour=$1
			;;
		* )
			echo >&2 \
			$usage_str
			exit 1
	esac
	shift
done

if [ $date == "" ]; then
  echo $usage_str
  exit 1
fi

Tricks

rm all files except some

FAQ

$(), backsticks \ and ${}`

$()\``用处相同,用于执行其中的命令 ${}用于参数替换,另,$10`会有隐藏的坑。

# https://superuser.com/questions/935374/difference-between-and-in-shell-script
$ cat myecho.sh
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
$ ./myecho.sh Hey diddle diddle, The cat and the fiddle, The cow jumped over the moon.
Hey diddle diddle, The cat and the fiddle, The Hey0 Hey1 Hey2 Hey3 Hey4 Hey5

Online Reference

Leftovers

Questions

TO-DOs

References