testコマンドだけ使ってif文を使わない方法

まずは、if文の確認。
ファイルの存在チェックする関数をif文を使って作ります。

~$ f(){
> if [ -f file1 ];then
>   echo FOUND
> else
>   echo NOT FOUND
> fi
> }
~$ 

file1という名前のファイルが存在していたら、FOUND表示。存在していなかったらNOT FOUNDを表示をする関数です。

使ってみます。file1が存在しない時。

~$ ls
~$ f
NOT FOUND

file1が存在する時(touchで作成)。

~$ touch file1
~$ ls
file1
~$ f
FOUND

関数fは、testコマンドを使うとこのように書き換えできます。

~$ ls
~$ if test -f file1;then echo FOUND;else echo NOT FOUND;fi
NOT FOUND
~$ touch file1
~$ if test -f file1;then echo FOUND;else echo NOT FOUND;fi
FOUND
~$ 

&&や||を使えば、if文自体を省略できます。

Trueかどうかのチェック。

~$ ls
file1
~$ test -f file1 && echo FOUND
FOUND

Falseかどうかのチェック。

~$ test -f file1 || echo NOT FOUND

&&と||を2つとも使えばif~else~fiと同じことができます。

~$ f(){
> test -f file1 && echo FOUND || echo NOT FOUND
> }
~$ 

使ってみましょう。

~$ ls
~$ f
NOT FOUND
~$ touch file1
~$ f
FOUND
~$ 

One response to “testコマンドだけ使ってif文を使わない方法

  1. I was just looking at your testコマンドだけ使ってif文を使わない方法 | コマンドの達人 website and see that your website has the potential to become very popular. I just want to tell you, In case you didn’t already know… There is a website network which already has more than 16 million users, and the majority of the users are interested in websites like yours. By getting your website on this network you have a chance to get your site more popular than you can imagine. It is free to sign up and you can find out more about it here: http://thfox.com/500s – Now, let me ask you… Do you need your website to be successful to maintain your business? Do you need targeted traffic who are interested in the services and products you offer? Are looking for exposure, to increase sales, and to quickly develop awareness for your site? If your answer is YES, you can achieve these things only if you get your site on the service I am describing. This traffic network advertises you to thousands, while also giving you a chance to test the service before paying anything at all. All the popular blogs are using this service to boost their traffic and ad revenue! Why aren’t you? And what is better than traffic? It’s recurring traffic! That’s how running a successful site works… Here’s to your success! Find out more here: http://s.t0m-s.be/5q

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA