Shell 脚本备忘

文章目录
  1. 1. 结果赋值
  2. 2. 文件名操作
  3. 3. 检查文件
  4. 4. 打包参数列表
  5. 5. 打印目录树
  6. 6. 递归列出所有文件

结果赋值

1
variable=$(command –options arguments)

文件名操作

1
2
3
filename=$(basename "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"

检查文件

1
2
3
4
5
6
7
8
#!/bin/bashv
file="/etc/hosts"
if [ -f "$file" ]
then
echo "$file found."
else
echo "$file not found."
fi
Commands Comments
-b FILE FILE exists and is block special
-c FILE FILE exists and is character special
-d FILE FILE exists and is a directory
-e FILE FILE exists
-f FILE FILE exists and is a regular file
-g FILE FILE exists and is set-group-ID
-G FILE FILE exists and is owned by the effective group ID
-h FILE FILE exists and is a symbolic link (same as -L)
-k FILE FILE exists and has its sticky bit set
-L FILE FILE exists and is a symbolic link (same as -h)
-O FILE FILE exists and is owned by the effective user ID
-p FILE FILE exists and is a named pipe
-r FILE FILE exists and read permission is granted
-s FILE FILE exists and has a size greater than zero
-S FILE FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE FILE exists and its set-user-ID bit is set
-w FILE FILE exists and write permission is granted
-x FILE FILE exists and execute (or search) permission is granted

打包参数列表

1
2
3
4
5
6
ARGS=(
-Dxxx=xxx
-Dyyy=yyy
)

cmake "${ARGS[@]}"

打印目录树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/sh
#######################################################
# UNIX TREE #
# Version: 2.4 #
# File: ~/apps/tree/tree.sh #
# #
# Displays Structure of Directory Hierarchy #
# ------------------------------------------------- #
# This tiny script uses "ls", "grep", and "sed" #
# in a single command to show the nesting of #
# sub-directories. The setup command for PATH #
# works with the Bash shell (the Mac OS X default). #
# #
# Setup: #
# $ cd ~/apps/tree #
# $ chmod u+x tree.sh #
# $ ln -s ~/apps/tree/tree.sh ~/bin/tree #
# $ echo "PATH=~/bin:\${PATH}" >> ~/.profile #
# #
# Usage: #
# $ tree [directory] #
# #
# Examples: #
# $ tree #
# $ tree /etc/opt #
# $ tree .. #
# #
# Public Domain Software -- Free to Use as You Like #
# centerkey.com/tree - By Dem Pilafian #
#######################################################

echo
if [ "$1" != "" ] #if parameter exists, use as base folder
then cd "$1"
fi
pwd
ls -R | grep ":$" | \
sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
# 1st sed: remove colons
# 2nd sed: replace higher level folder names with dashes
# 3rd sed: indent graph three spaces
# 4th sed: replace first dash with a vertical bar
if [ $(ls -F -1 | grep "/" | wc -l) = 0 ] # check if no folders
then echo " -> no sub-directories"
fi
echo
exit

递归列出所有文件

ls -R . | awk ‘
/:$/&&f{s=$0;f=0}
/:$/&&!f{sub(/:$/,””);s=$0;f=1;next}
NF&&f{ print s”/“$0 }’