2016-06-17 11 views
1

シェルスクリプトでは、いくつかの引数を渡した関数afunがあります。 私は、これらの引数の少なくとも一方が先験的に知られていない(それはa9*\|/(などの任意の文字可能性が与えられた文字が含まれている場合、私は見つけるのに役立ちます別の関数が必要です[などではなく、space):シェルスクリプト:文字列に文字( '*'や ''などの文字を含む)が含まれているかどうかをテストします。

afun() { 
    # Some commands here... 
    testchar=... # here I have some logic which decides what character should be tested below 
    # Now, call another function to test if any of the args to "afun" 
    # contain the character in var "testchar". 
    # If it does, print "Found character '$testchar' !" 
} 

提案機能はバッシュ、ダッシュ、灰ZSH少なくとも適合性であるべきである - 私は肝炎ためe Dockerコンテナにインストールされている異なるLinuxディストリビューション(Ubuntu、Alpine Linux)で実行する必要のあるスクリプト。特定のシェルインタプリタに依存することを宣言する必要はありません。以下は

+3

Bash、Dash、AshおよびZSH。あなたが冗談を言うように聞こえる。 ;)そして質問はあまり明確ではありません。 – sjsam

+0

ZSHにはAshよりも多くの機能がありますが、私が求めていることは不合理ですか?そして、ありがとう、変数名を固定しました( 'c 'ではなく' testchar'でなければなりません) – Elifarley

+0

不合理ではありませんが、非常に難しいはずですIMHO .. :( – sjsam

答えて

3

ここに私の提案シェル関数です:

charexists() { 
    char="$1"; shift 
    case "$*" in *"$char"*) return;; esac; return 1 
} 

そして、ここでは、あなたがそれを使用することができます方法は次のとおりです。

afun() { 
    # Some commands here... 
    testchar=... # here I have some logic which decides what character should be tested below 
    # Now, call another function to test if any of the args to "afun" 
    # contain the character in var "testchar". 
    # If it does, print "Found character '$testchar' !" 
    charexists "$testchar" "[email protected]" && echo "Found character '$testchar' !" 
} 

はここです単純単位テスト:

fun2test=charexists 
{ $fun2test '*' 'a*b' && printf 1 ;} ; \ 
{ $fun2test '*' 'a' '*' '\' 'b#c|+' '\' && printf 2 ;} ;\ 
{ $fun2test '\' 'a' '*' '\' 'b#c|+' '\' && printf 3 ;} ;\ 
{ $fun2test '*' 'ab' || printf 4 ;} ; \ 
{ $fun2test '*' 'a' '' '/' 'b#c|+' '\' || printf 5 ;}; echo 

5回のテストに合格すると、12345が表示されます。

私はちょうどBash、Dash、Ash、ZSHの下でテストして、うまくいった。

+1

'charexists" $ testchar "$ *' - '$ *'を引用符なしで - あなたの引数のリストに '*'が含まれていれば悪い挙動を示します。現在のディレクトリにあるファイル名を削除します。 –

+0

確かに!修正しました、ありがとう! – Elifarley

0

は、このために私のbashの具体的な解決策である:

#!/bin/bash 
fun() 
{ 
    not_allowed=' ' # Charater which is not allowed 
    [[ "$1" =~ $not_allowed ]] && echo "Character which is not allowed found" 
} 

fun "TestWithoutSpace" 
fun "Test with space" 
+0

私のソリューションで見つかったテストケースを使用して、あなたの提案されたソリューションは '34'だけを出力するので、最初の2つのテストは失敗します。 – Elifarley

関連する問題