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

问题描述

# !/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 行说“坏替换”。任何帮助请:)

解决方法

我建议尝试以下方法:

# !/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

,

关注和纠正castel我宁愿说:

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