use*_*436 0 gedit bash scripts
我正在学习 Bash,但有些东西在我的书中没有解释。首先我会发布一个脚本,然后我会通过脚本提出问题。
Bash 脚本:
$ cat sortmerg
#!/bin/bash
usage ()
{
if [ $# -ne 2 ]; then
echo "Usage: $0 file1 file2" 2>&1
exit 1
fi
}
# Default temporary directory
: ${TEMPDIR:=/tmp}
# Check argument count
usage "$@"
# Set up temporary files for sorting
file1=$TEMPDIR/$$.file1
file2=$TEMPDIR/$$.file2
# Sort
sort $1 > $file1
sort $2 > $file2
# Open $file1 and $file2 for reading. Use file descriptors 3 and 4.
exec 3<$file1
exec 4<$file2
# Read the first line from each file to figure out how to start.
read Line1 <&3
status1=$?
read Line2 <&4
status2=$?
# Strategy: while there is still input left in both files:
# Output the line that should come first.
# Read a new line from the file that line came from.
while [ $status1 -eq 0 -a $status2 -eq 0 ]
do
if [[ "$Line2" > "$Line1" ]]; then
echo -e "1.\t$Line1"
read -u3 Line1
status1=$?
else
echo -e "2.\t$Line2"
read -u4 Line2
status2=$?
fi
done
# Now one of the files is at end-of-file.
# Read from each file until the end.
# First file1:
while [ $status1 -eq 0 ]
do
echo -e "1.\t$Line1"
read Line1 <&3
status1=$?
done
# Next file2:
while [[ $status2 -eq 0 ]]
do
echo -e "2.\t$Line2"
read Line2 <&4
status2=$?
done
# Close and remove both input files
exec 3<&- 4<&-
rm -f $file1 $file2
exit 0
Run Code Online (Sandbox Code Playgroud)
问题:
首先,如何在 Gedit 中缩进代码?我从书中复制并粘贴了代码,它不会自动缩进代码。您通常使用 Gedit 或任何其他流行的用于编写 bash 脚本的编辑器吗?
: ${TEMPDIR:=/tmp}
你能解释一下这是什么吗?我有 C# 和其他编程语言的编程知识。所以你能告诉我,假设我不是编程的新手,:键和大括号键有什么作用?
if [[ "$Line2" > "$Line1" ]]; then
[]
与测试相同。但为什么会[[]]
有所不同呢?
status1=$?
什么是$?
?
提前谢谢了。
是的,您在 Gedit 中有缩进。打开 gedit 并在 Edit-> Preferences 你可以有自动缩进选项。
关于第二点,它的说法就像假设 TEMPDIR 在/tmp
位置。
我使用 vim 编写 shell 脚本。
${TEMPDIR}
将扩展为名为 TEMPDIR 的变量的值。${TEMPDIR:=/tmp}
会做同样的事情,但如果它是空的(或未设置),值 /tmp 将被分配给 TEMPDIR,并且也会被扩展。
有${TEMPDIR:=/tmp}
一行独自一人,将导致其变为如/tmp
将尝试执行/tmp
的命令(这显然会失败,因为你不能执行目录)。这就是使用:
(null) 命令的原因。null 命令忽略所有输入、所有参数,并且绝对不执行任何操作。运行help :
以查看该内置命令的描述。
请参阅http://mywiki.wooledge.org/BashFAQ/073了解您可以使用参数扩展执行的各种操作。
[[ "$line2" > "$Line1" ]]
如果 line2 在 line1 之后排序(如 C 中的 strcmp),则返回 true。
[("test" command) 和 [[ ("new test" command) 用于评估表达式。[[ 仅适用于 Bash、Zsh 和 Korn shell,并且功能更强大;[ 和 test 在 POSIX shell 中可用。
有关命令和关键字之间的差异,请参阅http://mywiki.wooledge.org/BashFAQ/031。[
[[
?
是一个特殊参数,用于保存最后执行的命令的退出状态。 $?
扩展该参数的值。
附带说明一下,如果这是你书中的一个例子,我会说这是学习 bash 的糟糕来源。我建议阅读http://mywiki.wooledge.org/BashGuide,它也教授了良好的实践。