I'm trying to display only one line of text when executing my code in bash. So for example if I was to run the following
./myscript.sh /etc
it would display all the lines in my script EX:
/etc is a directory
etc/hosts is a file
/dev/tty0 is a character device
/dev/sda is a block device
/MyNonExistantDirectory is not a file, directory, character device or block device on your system.
What I want it to display is
/etc is a directory
after using the command ./myscript.sh /etc
.
#!/bin/bash
device0="/etc"
if [ -d "$device0" ]
then
echo "$device0 is a directory."
fi
device1="/etc/hosts"
if [ -f "$device1" ]
then
echo "$device1 is a file."
fi
device2="/dev/tty0"
if [ -c "$device2" ]
then
echo "$device2 is a character device."
fi
device3="/dev/sda"
if [ -b "$device3" ]
then
echo "$device3 is a block device."
fi
device4="/MyNonExistantDirectory"
if [ -f "$device4" ]
then
echo "$device4 is not a file, directory, character device or block device on your system."
fi
Use $1
to get the argument. And use if/elif/else
to test mutually exclusive conditions.
#!/bin/bash
device=$1
if [ -d "$device" ]
then
echo "$device is a directory."
elif [ -f "$device" ]
then
echo "$device is a file."
elif [ -c "$device" ]
then
echo "$device is a character device."
elif [ -b "$device" ]
then
echo "$device is a block device."
else
echo "$device is not a file, directory, character device or block device on your system."
fi
You pretty much nailed it i think; all you need to do is make one "device" from the first positional argument ($1) and then convert your if statements per path into a single if statement with elif clauses.
#!/bin/bash
device=$1
if [ -d "$device" ]; then
echo "$device is a directory."
elif [ -f $device ]; then
echo "$device1 is a file."
elif [ -c $device ]; then
echo "$device2 is a character device."
elif [ -b $device ]; then
echo "$device3 is a block device."
else
echo "$device is not a file, directory, character device or block device on your system."
fi
the linux command head will show the top lines of a file. Therefore
head -1
I believe will produce the output you are looking for.
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.