LoginSignup
0
0

More than 3 years have passed since last update.

Linux bash使いのためのWindowsスクリプティング

Last updated at Posted at 2021-05-09

Linux bashではゴリゴリとスクリプト書いてるのに、Windowsになるといまいち書けないって人向けの記事。

Linuxでbashならこう書くんだけどなぁ、ってのをことあるごとに調べたくないので、そのためのまとめ。

はじめに

前提

  • WSL2とかを使えば、WindowsでもネイティブなLinux bashは使えるけど、商用環境向けで気軽にミドルウェア追加できないとか、そのためだけに構成変更できない(したくない)という状況向け。
  • Windows環境で最初から使える(主に)PowerShellやコマンドスクリプト(*.cmd)、VBSなどでの書き方がメイン。
  • 純開発者向けよりは半インフラ担当者向けかも(もちろん開発者がLinux向けのスクリプトをWindows向けにバックポートする際にも活用はできるものかと)。
  • PowerShellよりもコマンドスクリプトファースト(PowerShellは細かいバージョンの違いが面倒なため)←個人的な好みに近い
  • Linuxは主にRHEL(CentOS)を使用してますが基本どのディストリビューションのbash使いでも同じはず。

別の機会にWSL2の有効的な使い方、みたいなものも触れてみたい。

目次

  • おまじない系
    • 実行スクリプト名の取得
    • 実行ディレクトリ名の取得
  • プロセスID
  • ウェイトをかける
  • 関数の書き方
  • 遅延展開のさせ方
  • 制御文
    • IF分岐の書き方
    • 繰り返し処理の書き方

おまじない系

おまじない系/実行スクリプト名の取得

◇Bashの場合

basename.sh
#!/bin/bash
_LNAME=$(basename "$0")
echo "$_LNAME";
(実行結果)
basename.sh

◇Windows/コマンドスクリプトの場合

basename.cmd
@echo off
setlocal enabledelayedexpansion
set _LNAME=%~nx0 
echo.%_LNAME%
(実行結果)
basename.cmd

◇Windows/PowerShellの場合

basename.ps1
echo $MyInvocation.MyCommand.Name
(実行結果)
basename.ps1

おまじない系/実行ディレクトリ名の取得

◇Bashの場合

current_dir.sh
#!/bin/bash
_LNAME=$(dirname "$0")
echo "$_LNAME";
(実行結果)
/usr/local/src

◇Windows/コマンドスクリプトの場合

current_dir.cmd
@echo off
setlocal enabledelayedexpansion
set _LNAME=%~dp0 
echo.%_LNAME%
(実行結果)
C:\Users\hoge\My Test\

注意点はコマンドスクリプトの場合、末尾に\がつく点
嫌なら以下のように末尾を1文字削る。

current_dir.cmd
@echo off
setlocal enabledelayedexpansion
set _LNAME=%~dp0
set _LNAME=%_LNAME:~0,-1%   ←先頭から文字長-1きりとる、という意味
echo.%_LNAME%
(実行結果)
C:\Users\hoge\My Test

◇Windows/PowerShellの場合

current_dir.ps1
echo $(Split-Path $MyInvocation.MyCommand.Path -Parent)
(実行結果)
C:\Users\xxx\PowerShell

プロセスIDの取得方法

◇Bashの場合

process_id.sh
echo $$
sleep 30
(実行結果)
121

◇Windows/コマンドスクリプトの場合

コマンドスクリプトの場合は、実行しているスクリプトファイルのプロセスIDは取得できない
(コマンドプロンプトのcmd.exeのプロセスIDまでしか取得できない)。

◇Windows/PowerShellの場合

ウェイトをかける

◇Bashの場合

wait_cmd.sh
sleep 5

◇Windows/コマンドスクリプトの場合

wait_cmd.cmd
timeout 5 >NUL

◇Windows/PowerShellの場合

関数の書き方

◇Bashの場合

function any_function () {
    echo "test $1";
}

any_function "test"
(実行結果)
test test

◇Windows/コマンドスクリプトの場合

goto MAIN

:FUNCTIONS

:DO_MY_FUNC
    echo.%1
    exit /b

:MAIN
call :DO_MY_FUNC test
(実行結果)
test

◇Windows/PowerShellの場合

遅延展開のさせ方

◇Bashの場合

◇Windows/コマンドスクリプトの場合

◇Windows/PowerShellの場合

制御文

制御文/IF分岐の書き方

◇Bashの場合

if [ -f "/var/log/messages" ]; then
    ls -lah /var/log/messages;
else
   :
fi

◇Windows/コマンドスクリプトの場合

if exists xxx (
    echo.xxx
) else (
   echo.yyy
)

注意点
if ~ else ~ が全て1ステートメントとなっておりこの1ステートメントを評価した瞬間の環境変数が展開された状態で実行されるため、
ifやelseブロック内で、戻り値を受け取って環境変数として参照しようとしても参照できない。

制御文/繰り返し処理の書き方

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