简体   繁体   中英

'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:)

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. Please note that ls -al as just like ls -l but it also shows hidden files (those beginning with '.').

Using set to define variables is not really a best practice. Here's a suggestion about the usage of set .

Following and correcting castel I would rather say:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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