0
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?

サンプル linuxコマンド実行の短縮

Last updated at Posted at 2024-07-30

要件

同じlinuxコマンドが何度も使用する場合、作業を自動化したい

注意点

・コマンドの詳細内容は使うシーンによって異なると思うのであくまでベースソース

配慮したポイント

・繰り返し使うという前提の元、処理したファイルやディレクトリが存在するかどうかを確認して状態によってコマンドが停止しないようにした。
sleepを加えることで順番に動くように制御した。

#!/bin/bash

echo "sample.txt作成"
if [ ! -d "test_dir" ]; then
mkdir test_dir
fi

if [ ! -d "move_dir" ]; then
mkdir move_dir
fi

if [ ! -e "sample.txt" ]; then
touch sample.txt
fi

sleep 5

#sample.txt作成されていたらtest_dirにコピーする
if [ -e "sample.txt" ]; then
echo "sample.txtコピー"
#[ユーザー名]は自身の環境に置き換えて指定する
cp sample.txt /Users/[ユーザー名]/Documents/test_dir/sample.txt
sleep 5
fi

#sample.txt作成されていたらmove_dirに移動する
if [ -e "/Users/[ユーザー名]/Documents/test_dir/sample.txt" ]; then
echo "sample.txt移動"
mv /Users/[ユーザー名]/Documents/test_dir/sample.txt /Users/[ユーザー名]/Documents/move_dir/sample.txt
fi

ターミナル実行結果

MacBook-Pro:Documents$ ./echo.sh
sample.txt作成
sample.txtコピー
sample.txt移動

結果

sample.txtが作成できており、move_dirに移動ができている。
sample.txt自体は残っているため、コピーして移動したことが確認できる。
コピーの過程を見たい場合はshell実行後にtest_dirをじっと見てるとファイルがコピーされていることが確認できる。
image.png
image.png

0
0
3

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
0
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?