相关疑难解决方法(0)

什么时候需要双引号?

过去的旧建议是对任何涉及 a 的表达式加双引号$VARIABLE,至少在希望 shell 将其解释为单个项目的情况下,否则,内容中的任何空格$VARIABLE都会脱离 shell。

但是,我知道在较新版本的 shell 中,不再总是需要双引号(至少出于上述目的)。例如,在bash

% FOO='bar baz'
% [ $FOO = 'bar baz' ] && echo OK
bash: [: too many arguments
% [[ $FOO = 'bar baz' ]] && echo OK
OK
% touch 'bar baz'
% ls $FOO
ls: cannot access bar: No such file or directory
ls: cannot access baz: No such file or directory
Run Code Online (Sandbox Code Playgroud)

zsh,而另一方面,同样的三个命令成功。因此,基于此实验,似乎在 中bash可以省略 内部的双引号[[ ... ]],但不能省略内部 …

shell bash zsh shell-script quoting

147
推荐指数
1
解决办法
6万
查看次数

重定向运算符、标准输入和命令参数

我正在关注 William Shotts 的“Linux 命令行”。据我了解,>操作员将标准输出保存到文件中,并<从文件中获取标准输入。

如果键盘是默认的标准输入并且<只从某个文件中获取该输入,为什么ls -l不等同于ls < some_params.txtwhere some_params.txtwill contain -l

提前致谢

io-redirection

6
推荐指数
1
解决办法
296
查看次数

如何将文本文件中的一行向上或向下移动一行?

我有一些文本文件,我希望能够任何文件中的任意一行向上或向下移动一行(文件开头或结尾的行将保持原样)。我有一些工作代码,但它看起来很笨拙,我不相信我已经涵盖了所有边缘情况,所以我想知道是否有一些工具或范式可以更好地做到这一点(例如更容易理解代码(对于其他读者或我在 6 个月内),更容易调试,更容易维护;“更高效”不是很重要)。

move_up() {
  # fetch line with head -<line number> | tail -1
  # insert that one line higher
  # delete the old line
  sed -i -e "$((line_number-1))i$(head -$line_number $file | tail -1)" -e "${line_number}d" "$file"
}

move_down() {
  file_length=$(wc -l < "$file")
  if [[ "$line_number" -ge $((file_length - 1)) ]]; then
    # sed can't insert past the end of the file, so append the line
    # then delete the old line
    echo $(head -$line_number "$file" …
Run Code Online (Sandbox Code Playgroud)

sed text-processing

3
推荐指数
1
解决办法
2万
查看次数