大規模なファイルシステムで役立つBashスクリプトを試してみよう
ディレクトリ内の「ファイルだけ」を一覧表示したいと思ったことはありませんか?あるいは「ディレクトリだけ」を表示したい場面もあるでしょう。そんなときに役立つのが、GPLv3で公開されている今回紹介するスクリプトです。
もちろん、findコマンドを使えば同じことができます。
find . -maxdepth 1 -type f -print
しかし、この方法は入力が面倒で、出力も見づらく、lsコマンドが持つ便利な機能の一部を利用できません。lsとgrepを組み合わせるという手もあります。
ls -F . | grep -v /
とはいえ、これもやや冗長です。このスクリプトは、もっとシンプルな代替手段を提供してくれます。
使い方
このスクリプトには4つの主要な機能があり、呼び出すときの名前によって動作が変わります。lsfはファイルを一覧表示し、lsdはディレクトリを、lsxは実行可能ファイルを、lslはシンボリックリンクをそれぞれ表示します。
シンボリックリンクが利用できるため、スクリプトのコピーを複数インストールする必要はありません。そのおかげでディスク容量を節約でき、スクリプトの更新も容易になります。
スクリプトの仕組みは、検索処理をfindコマンドに任せ、見つかった各項目に対してlsを実行するというものです。この設計の利点は、スクリプトに渡した引数がそのままlsコマンドに引き継がれる点です。たとえば、ドットで始まる隠しファイルも含めてすべてのファイルを表示するには、次のようにします。
lsf -a
ディレクトリを詳細形式(ロングフォーマット)で表示したい場合は、lsdコマンドを使います。
lsd -l
複数の引数を指定することもできますし、ファイルやディレクトリのパスを渡すことも可能です。
次のコマンドは、カレントディレクトリの親ディレクトリと/usr/binディレクトリ内の全ファイルを、分類記号付きの詳細形式で一覧表示します。
lsf -F -l .. /usr/bin
ただし、現時点では再帰的な処理には対応していません。次のコマンドを実行しても、カレントディレクトリ内のファイルしか表示されません。
lsf -R
サブディレクトリへは降りていかないため、この点は将来的に改善されるかもしれません。
内部構造
スクリプトはトップダウン方式で書かれており、冒頭に関数定義が並び、実際の処理は末尾付近で行われます。中核となるのはわずか2つの関数です。parse_args()関数はコマンドラインを解析し、オプションとパス名を分離するとともに、スクリプト固有のオプションをlsコマンドのオプションから切り分けます。
list_things_in_dir()関数は、引数としてディレクトリ名を受け取り、そのディレクトリに対してfindコマンドを実行します。見つかった各項目は、表示のためにlsコマンドへ渡されます。
まとめ
これは、シンプルな機能を実現するためのシンプルなスクリプトです。作業時間を節約でき、大規模なファイルシステムを扱う際には意外なほど役立つことでしょう。
スクリプト本体
#!/bin/bash
# Script to list:
# directories (if called "lsd")
# files (if called "lsf")
# links (if called "lsl")
# or executables (if called "lsx")
# but not any other type of filesystem object.
# FIXME: add lsp (list pipes)
#
# Usage:
# <command_name> [switches valid for ls command] [dirname...]
#
# Works with names that includes spaces and that start with a hyphen.
#
# Created by Nick Clifton.
# Version 1.4
# Copyright (c) 2006, 2007 Red Hat.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3, or (at your
# option) any later version.
# It is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# ToDo:
# Handle recursion, eg: lsl -R
# Handle switches that take arguments, eg --block-size
# Handle --almost-all, --ignore-backups, --format and --ignore
main ()
{
init
parse_args ${1+"$@"}
list_objects
exit 0
}
report ()
{
echo $prog": " ${1+"$@"}
}
fail ()
{
report " Internal error: " ${1+"$@"}
exit 1
}
# Initialise global variables.
init ()
{
# Default to listing things in the current directory.
dirs[0]=".";
# num_dirs is the number of directories to be listed minus one.
# This is because we are indexing the dirs[] array from zero.
num_dirs=0;
# Default to ignoring things that start with a period.
no_dots=1
# Note - the global variables 'type' and 'opts' are initialised in
# parse_args function.
}
# Parse our command line
parse_args ()
{
local no_more_args
no_more_args=0 ;
prog=`basename $0` ;
# Decide if we are listing files or directories.
case $prog in
lsf | lsf.sh)
type=f
opts="";
;;
lsd | lsd.sh)
type=d
# The -d switch to "ls" is presumed when listing directories.
opts="-d";
;;
lsl | lsl.sh)
type=l
# Use -d to prevent the listed links from being followed.
opts="-d";
;;
lsx | lsx.sh)
type=f
find_extras="-perm /111"
;;
*)
fail "Unrecognised program name: '$prog', expected either 'lsd', 'lsf', 'lsl' or 'lsx'"
;;
esac
# Locate any additional command line switches for ls and accumulate them.
# Likewise accumulate non-switches to the directories list.
while [ $# -gt 0 ]
do
case "$1" in
# FIXME: Handle switches that take arguments, eg --block-size
# FIXME: Properly handle --almost-all, --ignore-backups, --format
# FIXME: and --ignore
# FIXME: Properly handle --recursive
-a | -A | --all | --almost-all)
no_dots=0;
;;
--version)
report "version 1.2"
exit 0
;;
--help)
case $type in
d) report "a version of 'ls' that lists only directories" ;;
l) report "a version of 'ls' that lists only links" ;;
f) if [ "x$find_extras" = "x" ] ; then
report "a version of 'ls' that lists only files" ;
else
report "a version of 'ls' that lists only executables";
fi ;;
esac
exit 0
;;
--)
# A switch to say that all further items on the command line are
# arguments and not switches.
no_more_args=1 ;
;;
-*)
if [ "x$no_more_args" = "x1" ] ;
then
dirs[$num_dirs]="$1";
let "num_dirs++"
else
# Check for a switch that just uses a single dash, not a double
# dash. This could actually be multiple switches combined into
# one word, eg "lsd -alF". In this case, scan for the -a switch.
# XXX: FIXME: The use of =~ requires bash v3.0+.
if [[ "x${1:1:1}" != "x-" && "x$1" =~ "x-.*a.*" ]] ;
then
no_dots=0;
fi
opts="$opts $1";
fi
;;
*)
dirs[$num_dirs]="$1";
let "num_dirs++"
;;
esac
shift
done
# Remember that we are counting from zero not one.
if [ $num_dirs -gt 0 ] ;
then
let "num_dirs--"
fi
}
list_things_in_dir ()
{
local dir
# Paranoia checks - the user should never encounter these.
if test "x$1" = "x" ;
then
fail "list_things_in_dir called without an argument"
fi
if test "x$2" != "x" ;
then
fail "list_things_in_dir called with too many arguments"
fi
# Use quotes when accessing $dir in order to preserve
# any spaces that might be in the directory name.
dir="${dirs[$1]}";
# Catch directory names that start with a dash - they
# confuse pushd.
if test "x${dir:0:1}" = "x-" ;
then
dir="./$dir"
fi
if [ -d "$dir" ]
then
if [ $num_dirs -gt 0 ]
then
echo " $dir:"
fi
# Use pushd rather passing the directory name to find so that the
# names that find passes on to xargs do not have any paths prepended.
pushd "$dir" > /dev/null
if [ $no_dots -ne 0 ] ; then
find . -maxdepth 1 -type $type $find_extras -not -name ".*" -printf "%f\000" \
| xargs --null --no-run-if-empty ls $opts -- ;
else
find . -maxdepth 1 -type $type $find_extras -printf "%f\000" \
| xargs --null --no-run-if-empty ls $opts -- ;
fi
popd > /dev/null
else
report "directory '$dir' could not be found"
fi
}
list_objects ()
{
local i
i=0;
while [ $i -le $num_dirs ]
do
list_things_in_dir i
let "i++"
done
}
# Invoke main
main ${1+"$@"}
-
自宅プリンターで両面印刷を自動化!シンプルなBashスクリプトの作り方
私の自宅にはレーザープリンターがあります。Hewlett Packard LaserJet Pro CP1525nwカラープリンターはやや古いモデルですが、何年もの間、安定してカラー印刷をこなしてくれる頼れる働き者です。数年前にRaspberry Piをプリントサーバーとして導入し、家庭内ネットワークに接続しました。 このLaserJetはホームオフィスにとって大きな戦力です。昨年会社を立ち上げて以来、クライアントとの打ち合わせやワークショップ、研修会用の資料印刷には、ずっとこの小さなレーザープリンターにお世話になってきました。 ただ、ひとつだけ不満があります。このプリンターは片面印刷にしか対
-
実用的な5つの例で学ぶBashスクリプト入門チュートリアル
Unix SedやUnix Awkシリーズと同様に、本シリーズではBashスクリプティングに関する記事を複数回にわたって公開します。実用的なサンプルを交えながら、Bashスクリプティングのテクニックを幅広く解説していきます。 シェルとは、ユーザーが入力したコマンドを解釈して実行するプログラムです。コマンドはユーザーが直接入力するか、「シェルスクリプト」と呼ばれるファイルから読み込まれます。 ユーザーからの入力を直接読み取る場合、そのシェルは対話型(インタラクティブ)シェルと呼ばれます。 一方、ファイルからコマンドを読み込んで実行する場合は非対話型(ノンインタラクティブ)シェルと呼ばれます。この