Linux SHELL 命令入門題目答案(一)


1、如何使用shell 打印 “Hello World!”

(1)如果你希望打印 !,那就不要將其放入雙引號中,或者你可以通過轉義字符轉義
(2)echo 'hello world!' 使用單引號echo 時,bash 不會對單引號中的變量求值

2、求變量的長度

var='hello world'
echo ${#var} \\ 11

3、$0 表示 SHELL 的名稱,是那種SHELL 一般為 bash $SHELL 為SHELL 的位置 /bin/bash

4、完成定義2個變量 no1=1,no2=2 no3=no1+no3 ,然后打印 no3

no1=2
no2=3
let no3=no1+no2
echo $no3

如果是 no3=$no1+$no2 會輸出什么?

5、完成判斷是否為root用戶的SHELL 命令

if [ $UID -ne 0 ]; then echo 'not root!'; else echo 'root!' ;fi

#if 中括號 杠相不相等,分號 then 直接跟語句 fi

6、shell 進行浮點數運算 1.5*4

var1=1.5
var2=4
result=`echo "$var1*$var2" | bc`

7、執行某條命令cmd,將正確及錯誤信息都輸入到 output.txt

cmd output.txt 2>&1 

8、使用寫一個腳本,運行時能夠將下面的內容放入 aa.txt

wget http://localhost:8080/obu-interface/index.jsp
netstat -anp | grep 8080

#!/bin/bash
cat <<EOF>aa.txt
wget http://localhost:8080/obu-interface/index.jsp
netstat -anp | grep 8080
EOF

9、定義一個含有4個元素的一維數組,並依次完成,打印其中的第2個元素,打印數組長度,打印所有元素

array_var=(1 2 3 4)
echo ${array_var[1]}
echo ${array_var[*]} 或 echo ${array_var[@]}
echo ${#array_var[*]} 或 echo ${#array_var[@]}

10、打印文件下所有的文本,非目錄

for file in `ls` ;
do
if [ -f $file ];
then
echo $file;
fi
done

11、按照這種格式輸出時間

2016-01-13 18:06:07 date '+%Y%m%d%H%M%S'

20160113180750 date '+%Y-%m-%d %T'

1452679772 date '+%s'

12、while 循環 10次 依次在屏幕的一行內打印 1-10,打印一次休眠1s

#!/bin/bash
echo -n Count:
count=0;
while true;
tput sc; #存儲光標位置
do
if [ $count -lt 4 ] ; then
sleep 1;
let count++;
tput rc; #恢復關標位置
tput ed; #清空光標后的內容
echo -n $count;
else
exit 0;
fi

done;

13、寫一斷代碼檢測一個命令 cmd 是否執行成功

#!/bin/bash
CMD="ls -l"
$CMD
if [ $? -eq 0 ] ; then
echo "$CMD executed successfully"
else
echo "$CMD executed failed"
fi

14、以下文件系統相關判斷分別是什么含義

[ -f $file ]

[ -d $file ]

[ -e $file ]

[ -w $file ]

[ -r $file ]

[ -x $file ]

15、SHELL 如何判斷兩個字符串是否相等、字符串比較大小、字符串是否為空

if [[ $str1 = $str2 ]]

if [[ $str1 > $str2 ]]

if [[ -z $str1 ]] #str1 為空 返回真

if [[ -n $str1 ]] #str1 非空 返回真

16、cat 顯示行號 cat -n test.txt

17、使用 find 命令 將某個文件夾下的所有txt 文件全部找到,並刪除、備份(或 拷貝到另一個目錄下),分別使用 -exec xargs 等命令

find /i -type f -name "*.txt" -exec cp {} /test \;
find /i -type f -name "*.txt" -exec rm -rf {} \;

find /i -type f -name "*.txt" -print | xargs rm -rf ;

find /i -type f -name "*.txt" -print | xargs -t -i cp {} {}.bak

# 大多數 Linux 命令都會產生輸出:文件列表、字符串列表等。但如果要使用其他某個命令並將前一個命令的輸出作為參數該怎么辦?例如,file 命令顯示文件類型(可執行文件、ascii 文本等);你能處理輸出,使其僅顯示文件名,目前你希望將這些名稱傳遞給 ls -l 命令以查看時間戳記。xargs 命令就是用來完成此項工作的。他允許你對輸出執行其他某些命令。

# -i 選項告訴 xargs 用每項的名稱替換 {}

18、使用tr 命令 將 HELLO WORLD 替換成小寫

echo "HELLO WORLD" | tr 'A-Z' 'a-z'

19、替換文件 text.txt 的所用 制表符為空格

cat text.txt | tr '\t' ''

20、使用 tr 命令 刪除數字

echo 'hello 124 world 345!'| tr -d '0-9' #-d 表示刪除

21、刪除Windows文件“造成”的'^M'字符

cat file | tr -s "\r" "\n" > new_file # -s 表示替換重復的字符串

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM