#-----------------------------------------------
$ printf "This script prints '%s, %s!'\n" Hello world
#-----------------------------------------------
#結果: This script prints 'Hello, world!'
Wed Dec 3 11:37:10 CST 2025
Untitled Document
Read (從 STDIN 輸入)
類似 C 語言中的 scanf,Shell 也提供一個從鍵盤 (STDIN) 輸入
的指令,'read' 格式如下:
Add variables to a program's environment without
permanently
affecting the environment of the shell or subsequent commands.
PATH=/bin:/usr/bin awk '...' file1 file2
This changes the value of PATH only for the execution of the single
awk command.
Any subsequent commands, however, see the current value of PATH
in their environment.
Used only by interactive shells upon invocation; the value
of $ENV is
parameter-expanded. The result should be a full pathname for a
file to be
read and executed at startup. This is an XSI requirement.
$HOME
Home (login) directory.
使用者自己的目錄
$IFS
Internal field separator; i.e., the list of characters that
act as word
separators. Normally set to space, tab, and newline.
$LANG
Default name of current locale; overridden by the other
LC_* variables.
$LC_ALL
Name of current locale; overrides LANG and the other LC_*
variables.
$LC_COLLATE
Name of current locale for character collation
(sorting) purposes.
$LC_CTYPE
Name of current locale for character class
determination during
pattern matching.
$LC_MESSAGES
Name of current language for output messages.
$LINENO
Line number in script or function of the line that just
ran.
$NLSPATH
The location of message catalogs for messages in
the language given by $LC_MESSAGES (XSI).
$PATH
Search path for commands. 執行命令時所搜尋的目錄
$PPID
Process ID of parent process.
$PS1
Primary command prompt string. Default is "$ ".
在命令列時的提示號
$PS2
Prompt string for line continuations. Default is "> ".
當命令尚未打完時,Shell 要求再輸入時的提示號
$PS4
Prompt string for execution tracing with set -x. Default is
"+ ".
$PWD
Current working directory.
其他幾個有用的環境變數
$TZ
時區
$MAILCHECK
每隔多少秒檢查是否有新的信件
$MANPATH
man 指令的搜尋路徑
Wed Dec 3 11:37:12 CST 2025
Untitled Document
Env
The env command
may be used to remove variables from a program's environment, or
to temporarily change environment variable values:
The -i option initializes the environment; i.e., throws away any
inherited
values, passing in to the program only those variables named on
the command line.
Wed Dec 3 11:37:12 CST 2025
Untitled Document
Unset
Removes variables and functions from the running shell.
unset full_name #Remove the full_name variable
unset -v first middle last #Remove the other variables
Use unset -f to remove functions:
who_is_on ( ) { #Define a function
who | awk '{ print $1 }' | sort -u #Generate sorted list of users
}
unset -f who_is_on #Remove the function
Early versions of the shell didn't have functions or the unset command.
POSIX added the -f option for removing functions, and then added the
-v option for symmetry with -f.
#讀取第一個txt檔,將之後的所有csv 檔內的逗號改成空白,全部串接在一起,輸出到 STDOUT#=========================================================================
cat $1
shift #捨棄第一個引數
for i
do
sed 's/,/ /g' $i #利用sed將逗號改成空白
done
Wed Dec 3 11:37:13 CST 2025
Untitled Document
I/O Redirection
Syntax
>file
write standard output to file
>>file
append standard output to file
>&m
write standard output to file descriptor m
<file
read standard intput from file
<&m
read standard input from file descriptor m
<<word
read standard input from a "here document"
Any of the file redirection syntaxes can be prefixed with a
file descriptor to specify
a file to be used in place of the default file for that syntax.
command 2> file
write standard error to file
#discard both standard output and standard error
command > /dev/null 2>&1
#wrong
command 2>&1 > /dev/null
Reading Files
while read LINE
do
command
done < file
Truncate a File
> file
: > file
cat /dev/null > file
Wed Dec 3 11:37:14 CST 2025
Untitled Document
Avoid File From Truncated by I/O Redirection
set -C
Execute command 'set -C' enables the shell's noclobber option.
redirections with plain > to preexisting files fail.
case $# in
0) echo Usage: xxxxxx ;;
1|2) process data ;;
*) echo Usage: xxxxx ;;
esac
echo 'Enter A, B, or C: \c'
read letter
case $letter in
A|a) echo 'You entered A.';;
B|b) echo 'You entered B.';;
C|c) echo 'You entered C.';;
*) echo 'Not A, B, or C';;
esac
Wed Dec 3 11:37:16 CST 2025
Untitled Document
流程控制 - for 迴圈
'for'迴圈是另個重要的流程控制。其格式如下:
for var in arg-list
do
commands
done
var 是迴圈變數,每一圈執行時,會從 arg-list 中逐次取用一個代入迴圈變數中
範例 Script
執行結果
for i in xx yy zz
do
echo $i
done
xx
yy
zz
Questions
What is the value of $i the first time through the loop?
假設一個使用者利用 C 語言在開發一個複雜的程式,而原始檔分散在數十甚至
上百個小檔案中,在開發過程中經常要反覆的檢查各原始碼,單純依靠終端機
是很痛苦的事,此時就可以利用 concatefile 這個script
將所有原始檔加上 line number 集中到一個檔案中,再印出來,方便
檢視。如果環境許可,甚至可貼在牆上那就更方便了。
number=0
while [ $number -lt 10 ]
do
echo "$number\c"
number=`expr $number + 1` #將變數 number 加一
done
echo
0123456789
Wed Dec 3 11:37:17 CST 2025
Untitled Document
流程控制 - break and continue
這兩者是用於for, while, until 等迴圈控制下。break 會跳至done後方執行
,而continue會跳至done執行,繼續執行迴圈。
範例
while
echo "Please enter data ('done' to exit):"
read response
do
if [ "$response" = "done" ]
then
break
fi
if [ "$response" = "" ]
then
continue
fi
_......
_......
process data
_......
_......
done
Wed Dec 3 11:37:17 CST 2025
Untitled Document
Function ( 函式 )
函式 (Function)
Wed Dec 3 11:37:17 CST 2025
Untitled Document
Function ( 函數/函式 )
幾乎所有的高階程式語言都必須提供副程式的功能,讓程式設計者可以將重複性的
任務寫成副程式,俾便重複使用,既能節省空間,程式也比較清爽,有助於對邏輯的
分析與理解。副程式在不同的程式語言中,有不同的名稱,在 C 與 Shell 中,叫做
函數或函式 (Function)、在物件導向(Objet-Oriented)程式中,稱為方法 (Method)。
#-------------------------------------
# Script: wait_for --- wait for a user to log in
# 用法: wait_for user [ sleeptime ]
#-------------------------------------
wait_for ( ) {
until who | grep "$1" > /dev/null
do
sleep ${2:-100}
done
}
wait_for clinton #Wait for clinton, check every 100 sec
wait_for obama 60 #Wait for obama, check every 60 sec
equal ( ) {
test "$1" -eq "$2" && return 0 || return 1
}
equal "$a" "$b" && echo "$a and $b are equal"
equal "$c" "$d" || echo "$c and $d are not equal"
#-------------------------------------#測試看一個檔案是否含有某些字串#-------------------------------------
if grep pattern myfile > /dev/null
then
commands for true (Pattern is there)
else
commands for false (Pattern is not there)
fi
# -------------------------------------
# single quote vs double quote
# -------------------------------------
name=Clinton
echo 'My name is '$name' and today is '`date`
# -------------------------------------
echo "My name is $name and today is `date`"
file=
verbose=
quiet=
long=
while [ $# -gt 0 ] #Loop until no args left
do
case $1 in #Check first arg
-f) file=$2
shift #Shift off "-f" so that shift at end gets value in $2
;;
-v) verbose=true; quiet= ;;
-q) quiet=true; verbose= ;;
-l) long=true ;;
--) shift #By convention, - - ends options
break
;;
-*) echo $0: $1: unrecognized option >&2 ;;
*) break ;; # Nonoption argument, break while loop
esac
shift #Set up for next iteration
done