2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CLI プログラム引数の ~ の扱い

Posted at

CLI プログラムに ~ を引数として渡すと、何もせずとも受け取ったプログラムでホームディレクトリのパス($HOME 相当)に展開されます。この仕様を知らなくてハマりました。

再現手順

以下のプログラムをコンパイルします。

tilda.c
# include <stdio.h>

int main(int argc, char *argv[]) {
    printf("%s\n", argv[1]);
    return 0;
}

以下のようにコンパイルします。

$ clan tilda.c

以下のように実行します。

$ ./a.out ~
/Users/ogata

引数を ~ ではなく "~" または '~' にすることでホームディレクトリに展開されなくなります。

$ ./a.out "~"
~

再現環境

少なくとも以下の環境で同じ動作になります。

  • macOS 10.13.6
  • Ubuntu 18.04
  • FreeBSD 9.1-RELEASE-p24

補足

これは C 言語に限った話ではありません。例えば以下の Haskell でも同様の動作になります。

tilda.hs
import System.Environment

main = getArgs >>= putStrLn . head

Python でも同様です。

tilda.py
# !/usr/bin/python

import sys

print sys.argv[1]

Ruby でも同様です。

tilda.rb
# !/usr/bin/ruby

puts ARGV[0]

Perl でも同様です。

tilda.pl
# !/usr/bin/perl

print $ARGV[0];

プログラム言語や OS というよりは、シェル(本環境では bash)の「チルダ展開」の仕様のようです。シェルの展開に関してはシェルの展開順序に気をつけよう - Qiita が詳しいです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?