在一个 bash
shell,设置变量,只需使用 set NAME=bob
要么 set VITAL_SIGNS=none
。
您还可以通过调用命令的输出来设置变量 bash
-builtin功能 read
将输出分配给命名变量。这在管道流中运行良好,如下所示:
ls -l | wc -l | read NUMBER_OF_LINES
或者您可以将输出直接分配给变量,如下所示:
LICENSE_KEY=$(cat ~/software/key.txt | grep KEY | awk '{print $1}')
递归读取变量的一种好方法是循环,如下所示:
for BROKEN_LINK in $(commands to produce a list of files)
do
commands here to sort your links out, noting that the broken links are stored in the variable $BROKEN_LINKS
done
考虑到上述情况,以下内容应该有效:
证明文件夹不存在
StuffeMac:dan stuffe$ ls ~/Desktop/broken_links
ls: /Users/stuffe/Desktop/broken_links: No such file or directory
证明一个新的目标文件夹确实存在
StuffeMac:dan stuffe$ ls ~/Desktop/working_links
StuffeMac:dan stuffe$
创建一些无效且有效的链接
StuffeMac:dan stuffe$ ln -s ~/Desktop/brokenlinks/dan1
StuffeMac:dan stuffe$ ln -s ~/Desktop/brokenlinks/dan2
StuffeMac:dan stuffe$ ln -s ~/Desktop/working_links/dan3
StuffeMac:dan stuffe$ ln -s ~/Desktop/outofscopedeadlinks/dan4
StuffeMac:dan stuffe$ ls -l
total 32
lrwxr-xr-x 1 stuffe staff 38 8 Dec 10:06 dan1 -> /Users/stuffe/Desktop/brokenlinks/dan1
lrwxr-xr-x 1 stuffe staff 38 8 Dec 10:06 dan2 -> /Users/stuffe/Desktop/brokenlinks/dan2
lrwxr-xr-x 1 stuffe staff 40 8 Dec 10:06 dan3 -> /Users/stuffe/Desktop/working_links/dan3
lrwxr-xr-x 1 stuffe staff 46 8 Dec 10:21 dan4 -> /Users/stuffe/Desktop/outofscopedeadlinks/dan4
将死链接列表抓取到文件中以进行输入
StuffeMac:dan stuffe$ find . -type l | while read f; do if [ ! -e "$f" ]; then ls "$f" >> deadlinks.txt; fi; done
StuffeMac:dan stuffe$ more deadlinks.txt
./dan1
./dan2
./dan4
针对每个死链接运行一个循环
StuffeMac:dan stuffe$ for DEAD_LINK in $(cat deadlinks.txt)
> do
> DESTINATION_IN_SCOPE=$(readlink $DEAD_LINK | grep brokenlinks | wc -l)
> NEW_DESTINATION="~/Desktop/working_links/"
> if [ $DESTINATION_IN_SCOPE = "1" ]
> then
> NEW_LINK=$(echo $DEAD_LINK | colrm 1 2)
> ln -f -s $NEW_DESTINATION$NEW_LINK $DEAD_LINK
> else
> echo "Link $DEAD_LINK not in target folder"
> fi
> done
Link ./dan4 not in target folder
StuffeMac:dan stuffe$
编辑后检查符号链接
StuffeMac:dan stuffe$ ls -l
total 32
lrwxr-xr-x 1 stuffe staff 28 8 Dec 10:08 dan1 -> ~/Desktop/working_links/dan1
lrwxr-xr-x 1 stuffe staff 28 8 Dec 10:08 dan2 -> ~/Desktop/working_links/dan2
lrwxr-xr-x 1 stuffe staff 40 8 Dec 10:06 dan3 -> /Users/stuffe/Desktop/working_links/dan3
lrwxr-xr-x 1 stuffe staff 46 8 Dec 10:21 dan4 -> /Users/stuffe/Desktop/outofscopedeadlinks/dan4
Run: Command not found