如何在bash中显示一行文本

时间:2017-09-19 16:18:39

标签: linux bash input scripting

我在bash中执行代码时只尝试显示一行文本。  例如,如果我要运行以下

./myscript.sh /etc 

它将显示我的脚本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.

我希望它显示的是

/etc is a directory

使用命令./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

3 个答案:

答案 0 :(得分:1)

使用$1获取参数。并使用if/elif/else来测试互斥条件。

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

答案 1 :(得分:1)

我认为你几乎钉了它;你需要做的就是制作一个"设备"从第一个位置参数($ 1)开始,然后将每个路径的if语句转换为带有elif子句的单个if语句。

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

答案 2 :(得分:0)

linux命令头将显示文件的顶行。因此

head -1 

我相信会产生你想要的输出。