[英]How do you display one line of text in bash
在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
使用$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)中創建一個“設備”,然后將每個路徑的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
linux命令頭將顯示文件的頂行。 因此
head -1
我相信會產生您想要的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.