我在這里有一個簡單的代碼,但在理解它時遇到了一些麻煩。
$ more $1 | head -$2 | tail -1
對于第二個引數,我正在運行一個測驗 txt
$ more joe.txt
i am trying
something
else
to
see
if
head
works
the way
it
should
work
當我運行腳本時,我收到錯誤:
$ ./sample.sh jad.txt joe.txt
head: invalid option -- 'j'
Try 'head --help' for more information.
當我洗掉-前面的$2.
這是我在網上找到的一個練習題,我懷疑他們在這個問題上犯了錯誤。所以要么我在這里遺漏了一些東西,要么我做錯了。
當我在沒有-前面的情況下運行它時,$2我得到了這個:
./sample.sh jad.txt joe.txt
it
我的問題是:
- 為什么它只在
tail -1使用時才列印“它”?據我了解,tail 列印最后 10 行。那么-1做什么呢? - 符號是否
-應該在 前面做某事$2?
uj5u.com熱心網友回復:
-在引數之前通常意味著它是程式的一個短(一個字符)選項。--通常意味著它是一個長(多個字符)選項。這只是按照慣例。有很多例外。
所以,運行時:
./sample.sh jad.txt joe.txt
你的線
more $1 | head -$2 | tail -1
變成:
more jad.txt | head -joe.txt | tail -1
這讓人head抱怨。你給了它一個-joe.txt被解釋為短選項-j但head沒有選項的-j選項。
那么
-1做什么呢?
tail -1表示列印輸入的最后1一行。
tail -2表示列印輸入的最后2一行。
等...
head -1表示從輸入中列印第一1行。
head -2表示從輸入中列印第一2行。
ETC...
uj5u.com熱心網友回復:
It's not a mistake if you invoke it correctly (assuming this is the output you expect):
./sample.sh joe.txt 5
see
./sample.sh joe.txt 4
to
./sample.sh joe.txt 3
else
what it's a mistake is not checking for valid options in sample.sh
You should do something like
#! /bin/bash
usage() {
printf 'usage: %s file number\n' "$0" >&2
exit 1
}
if [[ $# != 2 ]]
then
usage
fi
re='^[0-9] $'
if ! [[ "$2" =~ $re ]]
then
printf 'ERROR: not a number: %s\n' "$2" >&2
usage
fi
more "$1" | head -n $2 | tail -1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491430.html
