简体   繁体   English

如何在bash中显示一行文本

[英]How do you display one line of text in bash

I'm trying to display only one line of text when executing my code in bash. 在bash中执行代码时,我试图仅显示一行文本。 So for example if I was to run the following 例如,如果我要运行以下命令

./myscript.sh /etc 

it would display all the lines in my script EX: 它会在我的脚本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 . 在使用命令./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. 使用$1来获取参数。 And use if/elif/else to test mutually exclusive conditions. 并使用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

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. 您要做的就是从第一个位置参数($ 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

the linux command head will show the top lines of a file. linux命令头将显示文件的顶行。 Therefore 因此

head -1 

I believe will produce the output you are looking for. 我相信会产生您想要的输出。

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

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