【问题标题】:'bad substitution' in linux shell scriptinglinux shell脚本中的“错误替换”
【发布时间】:2021-05-04 08:01:33
【问题描述】:
# !/bin/sh
echo "Enter file name:"
read fname
set ${ls -la $fname}
echo "The size of test.sh is $5 byte"
exit 0

我想编写一个可以在 linux shell 脚本中使用“set”命令打印文件大小的代码,所以我使用 ls -la 但它不起作用,我的终端只是在第 4 行显示“错误替换”。任何帮助请:)

【问题讨论】:

  • 我认为您的意思是使用$(),而不是${}。不过,不确定您想对lsset 的输出做什么。也许你的意思是set -- $(ls -la "$fname"),但那似乎是fragile

标签: shell scripting


【解决方案1】:

我建议尝试以下方法:

# !/bin/sh
echo "Enter file name:"
read fname
SIZE=$(ls -l "${fname}" |awk '{print $5}')
echo "The size of ${fname} is ${SIZE} bytes"
exit 0

SIZE 变量将包含读取文件名的大小。请注意ls -alls -l 一样,但它也显示隐藏文件(以'.' 开头的文件)。

使用set 定义变量并不是最佳实践。 Here's a suggestion about the usage of set.

【讨论】:

  • 我认为一旦有了括号就不需要了,但很高兴根据良好的反馈进行改进。谢谢!
  • 括号不会阻止扩展(出于其他原因它们很好,但在这种情况下没有区别)。试试a='*' ; echo ${a}a='*' ; echo "${a}"
【解决方案2】:

跟随并纠正castel我宁愿说:

# !/bin/sh
read -p "Enter file name: " fname
SIZE=$(ls -l "$fname" | awk '{print $5}')
echo "The size of $fname is $SIZE bytes"

【讨论】:

  • @Biffen:哎呀,对不起。还在第二次出现 fname 周围添加了引号。
猜你喜欢
  • 2022-01-13
  • 2014-01-14
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 2012-08-20
相关资源
最近更新 更多