简体   繁体   English

linux shell 脚本中的“错误替换”

[英]'bad substitution' in linux shell scripting

# !/bin/sh
echo "Enter file name:"
read fname
set ${ls -la $fname}
echo "The size of test.sh is $5 byte"
exit 0

I want to make a code which can print file size using 'set' command in linux shell script, so I use ls -la but it doesn't work and my terminal just says 'bad substitution' in line 4. Any help pls:)我想制作一个可以使用 linux shell 脚本中的“设置”命令打印文件大小的代码,所以我使用 ls -la 但它不起作用,我的终端只是在第 4 行显示“错误替换”。任何帮助请: )

I would suggest to try the following:我建议尝试以下方法:

# !/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 variable will contain the size of the read filename. SIZE变量将包含读取文件名的大小。 Please note that ls -al as just like ls -l but it also shows hidden files (those beginning with '.').请注意, ls -alls -l一样,但它也显示隐藏文件(以“.”开头的文件)。

Using set to define variables is not really a best practice.使用set来定义变量并不是真正的最佳实践。 Here's a suggestion about the usage of set .这是关于 set 用法的建议

Following and correcting castel I would rather say:跟随并纠正castel我宁愿说:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM