Linux shell 入门

By notsobad


What is shell?

Shell is a program that takes your commands from the keyboard and gives them to the operating system to perform

  • Shell vs GUI
  • sh, bash, dash, zsh

What is bash?

Bash is the GNU Project’s shell. Bash is the Bourne Again SHell. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard.


Bash 语法

  • 注释
  • 变量定义以及使用
  • 控制结构
  • 循环
  • 函数
  • 调试
  • 特殊字符
  • 执行方法

Hello world.

#!/bin/bash

# hello world example.
for i in `seq 1 10`;do
	echo hello world;
done

variables

a=1

b=$a

c=$a$b # or c="$a$b" or c=${a}${b}

d=$(($a + $b))

echo $HOME

env

commands

shell内置了一些命令,这些命令不需要调用外部程序,如echo, printf, cd, pwd等。

notsobad@box ~ $ type cd
cd is a shell builtin

notsobad@box ~ $ type find
find is /usr/bin/find

notsobad@box ~ $ a(){ id; }
notsobad@box ~ $ type a
a is a function
a ()
{
    id
}

if

See: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html


uid=`id -u`
if [ $uid -eq 1000 ]; then
	echo "uid is 1000"
fi

[ -f /etc/passwd ] && id
[ -z "$s" ] && id
[ `id -u` -eq 1000 ] && id
[ `uname` == "Linux" ] && id # string equal
[[ "abc" < "def" ]] && id # 避免 < 被识别为重定向

loop

 
for i in `ls /etc/*.conf`; do 
	echo "Got file $i"
done


while true;do
	date
    sleep 1
done

function

function x(){ 
	id; uname -a; 
}

x(){ 
	id; uname -a; 
}

y(){
	echo "$@";
}

debug

#!/bin/bash
set -x
# your shell script
set +x

or

bash -x x.sh

Special Characters

see http://tldp.org/LDP/abs/html/special-chars.html


run

sh file: x.sh

#!/bin/bash
id

run:

bash x.sh

# or

chmod +x x.sh
./x.sh

input and output

# stdout+stderr -> /dev/null
ls /tmp/x >/dev/null 2>&1

# stdout+stderr -> /dev/null
ls /tmp/x &>/dev/null

# stdout -> stderr
ls /tmp/x >&2

# stdout 
ls /tmp/x 

# subshell output redirect.
(ls /tmp/x; id) > /tmp/x 2>&1

keyboard shortcuts

  • ctl-A 到行首
  • ctl-B 光标倒退一个字符
  • ctl-C 退出当前程序
  • ctl-D 退出shell
  • ctl-E 到行尾
  • ctl-F 光标向后移动一个字符
  • ctl-K 删除光标向后的所有字符
  • ctl-L 清空终端
  • ctl-N 历史记录后翻
  • ctl-P 历史记录前翻
  • ctl-R 历史记录搜索

Real life scripts


学习资源