LoginSignup
46
21

More than 3 years have passed since last update.

touchでディレクトリごと作成(mkdir -p)する

Last updated at Posted at 2019-11-01

やりたいこと

1行で、存在しない ディレクトリごとファイルを作成したい!
要するに、以下のことを touch コマンドのみで以下のことをやりたいということです。

mkdir -p hoge/fugo/piyo
❯ touch hoge/fugo/piyo/test.txt
❯ tree .
.
└── hoge
    └── fugo
        └── piyo
            └── test.txt

3 directories, 1 file

シェルの設定ファイルにエイリアスとして登録して使えるまでがゴールです。

既存のtouchコマンド

touch存在しない ディレクトリごとファイルを作成しようとするとディレクトリがないよと怒られます。

touch hoge/fugo/piyo/test.txt
touch: hoge/fugo/piyo/test.txt: No such file or directory

シェルスクリプトを作成する

名前は適当ですが、一気通貫に作成するシェルスクリプトを作成します。

touch_mkdir.sh
#!/bin/sh

mkdir -p "$(dirname "$1")" && touch  "$1"

当方はzshを使用しているので、zshrcにエイリアスを登録します。
今回は mkdir + touch ということで mduch にしました。

zshrc
alias mduch='sh $HOME/dotfiles/lib/touch_mkdir.sh'

使ってみる

作成できました。簡単ですね!

❯ mduch hoge/fugo/piyo/text.txt
❯ tree .
.
└── hoge
    └── fugo
        └── piyo
            └── text.txt

3 directories, 1 file
46
21
2

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
46
21