Sysadm::Install(3pm)
π Sysadm::Install π β the Sysadm::Install(3pm) page, bestie edition
okay so. <rainbow>Sysadm::Install</rainbow> is a Perl module for Typical installation tasks for system administrators, and honestly? it's the moment. let's get into it π«Ά
β¨ NAME β¨
Sysadm::Install β typical installation tasks for system administrators. no cap, that's the whole vibe. π
π SYNOPSIS π
use Sysadm::Install qw(:all);
my $INST_DIR = '/home/me/install/';
cd($INST_DIR);
cp("/deliver/someproj.tgz", ".");
untar("someproj.tgz");
cd("someproj");
# Write out ...
blurt("Builder: Mike\nDate: Today\n", "build.dat");
# Slurp back in ...
my $data = slurp("build.dat");
# or edit in place ...
pie(sub { s/Today/scalar localtime()/ge; $_; }, "build.dat");
make("test install");
# run a cmd and tap into stdout and stderr
my($stdout, $stderr, $exit_code) = tap("ls", "-R");
likeβ¦ look at that. clean. iconic. π¦
πΈ DESCRIPTION πΈ
bestie, have you ever wished your installation shell scripts would just run reproducibly, without much programming fuzz, and even with optional logging turned on? π then it's giving "give up shell programming, use Perl."
Sysadm::Install executes shell-like commands performing typical installation tasks: copying files, extracting tarballs, calling make. and it has a "fail once and die" policy β it meticulously checks the result of every single operation and calls die() immediately if anything fails. it does not play. π
Sysadm::Install also supports a dry_run mode, where it logs everything but suppresses any write actions. lowkey the safest vibe. dry run mode is enabled by calling Sysadm::Install::dry_run(1). to switch back to normal, call Sysadm::Install::dry_run(0).
as of version 0.17, Sysadm::Install supports a confirm mode, where it interactively asks the user before running any of its functions (just like rm -i). confirm mode is enabled by calling Sysadm::Install::confirm(1). to switch back to normal, call Sysadm::Install::confirm(0).
Sysadm::Install is fully Log4perl-enabled. to start logging, just initialize Log::Log4perl. Sysadm::Install acts as a wrapper class, meaning that file names and line numbers are reported from the calling program's point of view. π
π§ FUNCTIONS π§
cp($source, $target)β copy a file from$sourceto$target.targetcan be a directory. heads up though:cpdoesn't copy file permissions. if you want the target file to reflect the source file's user rights, useperm_cp()shown below. π«Άmv($source, $target)β move a file from$sourceto$target.targetcan be a directory. simple as.download($url)β download a file specified by$urland store it under the name returned bybasename($url). yes bestie, it names it for you. πuntar($tarball)β untar the tarball in$tarball, which typically adheres to thesomeproject-X.XX.tgzconvention. but regardless of whether the archive actually contains a top directorysomeproject-X.XX, this function will behave if it had one. if it doesn't have one, a new directory is created before the unpacking takes place. unpacks the tarball into the current directory, no matter where the tarfile is located. π
please note that if you're using a compressed tarball (.tar.gzor.tgz), you'll needIO::Zlibinstalled. don't forget or you'll be sad. π
untar_in($tar_file, $dir)β untar the tarball in$tgz_filein directory$dir. create$dirif it doesn't exist yet. it just handles it. β¨pick($prompt, $options, $default, $opts)β ask the user to pick an item from a displayed list.$promptis the text displayed,$optionsis a referenc to an array of choices, and$defaultis the number (starting from 1, not 0) of the default item. for example,
pick("Pick a fruit", ["apple", "pear", "pineapple"], 3);
will display the following:
[1] apple
[2] pear
[3] pineapple
Pick a fruit [3]>
if the user just hits Enter, pineapple (the default value) will be returned. note that 3 marks the 3rd element of the list, and is not an index value into the array. β
if the user enters 1, 2 or 3, the corresponding text string (apple, pear, pineapple will be returned by pick().
if the optional $opts hash has { tty => 1 } set, then the user response will be expected from the console, not STDIN. π
ask($prompt, $default, $opts)β ask the user to either hit Enter and select the displayed default, or to type in another string.
if the optional $opts hash has { tty => 1 } set, then the user response will be expected from the console, not STDIN. π
mkd($dir)β create a directory of arbitrary depth, just likeFile::Path::mkpath. deep dirs? handled.rmf($dir)β delete a directory and all of its descendents, just likerm -rfin the shell.
bestie this is rm -rf energy. it deletes everything underneath. be so careful. π
cd($dir)β chdir to the given directory. if you don't want to havecd()modify the internal directory stack (used for subsequentcdback()calls), set thestack_updateparameter to a false value:
cd($dir, {stack_update => 0});
cdback()β chdir back to the last directory before a previouscd. if the optionresetis set, it goes all the way back to the beginning of the directory stack, i.e. no matter how manycd()calls were made in between, it'll go back to the original directory:
# go all the way back
cdback( { reset => 1 } );
make()β callmakein the shell. that's it, that's the function. π₯pie($coderef, $filename, ...)β simulateperl -pie 'do something' file. edits files in-place. expects a reference to a subroutine as its first argument. it will read out the file$filenameline by line and calls the subroutine setting a localized$_to the current line. the return value of the subroutine will replace the previous value of the line. β¨
example:
# Replace all 'foo's by 'bar' in test.dat
pie(sub { s/foo/bar/g; $_; }, "test.dat");
works with one or more file names.
if the files are known to contain UTF-8 encoded data, and you want it to be read/written as a Unicode strings, use the utf8 option:
pie(sub { s/foo/bar/g; $_; }, "test.dat", { utf8 => 1 });
plough($coderef, $filename, ...)β simulateperl -ne 'do something' file. iterates over all lines of all input files and calls the subroutine provided as the first argument. πΈ
example:
# Print all lines containing 'foobar'
plough(sub { print if /foobar/ }, "test.dat");
works with one or more file names.
if the files are known to contain UTF-8 encoded data, and you want it to be read into Unicode strings, use the utf8 option:
plough(sub { print if /foobar/ }, "test.dat", { utf8 => 1 });
my $data = slurp($file, $options)β slurps in the file and returns a scalar with the file's content. if called without argument, data is slurped from STDIN or from any files provided on the command line (like<>operates). π¦
if the file is known to contain UTF-8 encoded data and you want to read it in as a Unicode string, use the utf8 option:
my $unicode_string = slurp( $file, {utf8 => 1} );
blurt($data, $file, $options)β opens a new file, prints the data in$datato it and closes the file. if$options->{append}is set to a true value, data will be appended to the file. default is false, existing files will be overwritten. π
if the string is a Unicode string, use the utf8 option:
blurt( $unicode_string, $file, {utf8 => 1} );
blurt_atomic($data, $file, $options)β write the data in$datato a file$file, guaranteeing that the operation will either complete fully or not at all. this is accomplished by first writing to a temporary file which is thenrename()ed to the target file. all-or-nothing, main character energy. π
unlike in blurt, there is no $append mode in blurt_atomic.
if the string is a Unicode string, use the utf8 option:
blurt_atomic( $unicode_string, $file, {utf8 => 1} );
($stdout, $stderr, $exit_code) = tap($cmd, @args)β run a command$cmdin the shell, and pass it@argsas args. capture STDOUT and STDERR, and return them as strings. if$exit_codeis0, the command succeeded. if it is different, the command failed and$exit_codeholds its exit code.
please note thattap()is limited to single shell commands, it won't work with output redirectors ("ls >/tmp/foo" 2>&1). π
in default mode, tap() will concatenate the command and args given and create a shell command line by redirecting STDERR to a temporary file. tap("ls", "/tmp"), for example, will result in
'ls' '/tmp' 2>/tmp/sometempfile |
note that all commands are protected by single quotes to make sure arguments containing spaces are processed as singles, and no globbing happens on wildcards. arguments containing single quotes or backslashes are escaped properly. π
if quoting is undesirable, tap() accepts an option hash as its first parameter,
tap({no_quotes => 1}, "ls", "/tmp/*");
which will suppress any quoting:
ls /tmp/* 2>/tmp/sometempfile |
or, if you prefer double quotes, use
tap({double_quotes => 1}, "ls", "/tmp/$VAR");
wrapping all args so that shell variables are interpolated properly:
"ls" "/tmp/$VAR" 2>/tmp/sometempfile |
another option is utf8 which runs the command in a terminal set to UTF8. π
Error handling: by default, tap() won't raise an error if the command's return code is nonzero, indicating an error reported by the shell. if bailing out on errors is requested to avoid return code checking by the script, use the raise_error option:
tap({raise_error => 1}, "ls", "doesn't exist");
in DEBUG mode, tap logs the entire stdout/stderr output, which can get too verbose at times. to limit the number of bytes logged, use the stdout_limit and stderr_limit options
tap({stdout_limit => 10}, "echo", "123456789101112");
$quoted_string = qquote($string, [$metachars])β put a string in double quotes and escape all sensitive characters so there's no unwanted interpolation. e.g., if you have something like
print "foo!\n";
and want to put it into a double-quoted string, it will look like
"print \"foo!\\n\""
sometimes, not only backslashes and double quotes need to be escaped, but also the target environment's meta chars. a string containing
print "$<\n";
needs to have the '$' escaped like
"print \"\$<\\n\";"
if you want to reuse it later in a shell context:
$ perl -le "print \"\$<\\n\";"
1212
qquote() supports escaping these extra characters with its second, optional argument, consisting of a string listing all escapable characters:
Okay so check it β once you've escaped the code, it just... works:
my $script = 'print "$< rocks!\\n";';
my $escaped = qquote($script, '!$'); # Escape for shell use
system("perl -e $escaped");
=> 1212 rocks!
ate and left no crumbs π
And bestie, there's a shortcut for shells: by specifying ':shell' as the metacharacters string, qquote() will actually use `'!$``.
So picture this β you wanna run the perl code
print "foobar\n";
via
perl -e ...
on some box via ssh. You'd do:
use Sysadm::Install qw(qquote);
my $cmd = 'print "foobar!\n"';
$cmd = "perl -e " . qquote($cmd, ':shell');
$cmd = "ssh somehost " . qquote($cmd, ':shell');
print "$cmd\n";
system($cmd);
and get
ssh somehost "perl -e \"print \\\"foobar\\\!\\\\n\\\"\""
which runs on "somehost" without hickup and prints "foobar!". π₯ no notes, honestly.
Also Sysadm::Install comes with a script one-liner (installed in bin), which takes arbitrary perl code on STDIN and transforms it into a one-liner:
$ one-liner
Type perl code, terminate by CTRL-D
print "hello\n";
print "world\n";
^D
perl -e "print \"hello\\n\"; print \"world\\n\"; "
iconic behavior β¨
$quoted_string = quote($string, [$metachars]) β basically qquote()'s sibling π it puts a string in single quotes and escapes what needs to be escaped.
Heads up bestie: shells typically don't support escaped single quotes within single quotes, which means that
$ echo 'foo\'bar'
>
is invalid and the shell just sits there waiting until it finds a closing quote. π awkward.
Instead, there's an evil trick which gives the desired result:
$ echo 'foo'\''bar' # foo, single quote, \, 2 x single quote, bar
foo'bar
It uses the fact that shells interpret back-to-back strings as one. The construct above consists of three back-to-back strings:
(1) 'foo'
(2) '
(3) 'bar'
which all get concatenated to a single
foo'bar
If you call quote() with $metachars set to :shell, it will perform that magic behind the scenes:
print quote("foo'bar");
# prints: 'foo'\''bar'
perm_cp($src, $dst, ...) β reads the $src file's user permissions and modifies all $dst files to reflect the same permissions. π matchy-matchy, on purpose.
owner_cp($src, $dst, ...) β reads the $src file/directory's owner uid and group gid and applies it to $dst.
For example: copy uid/gid of the containing directory to a file therein:
use File::Basename;
owner_cp( dirname($file), $file );
Usually requires root privileges, just like chown does. π
$perms = perm_get($filename) β reads the $filename's user permissions and owner/group. Returns an array ref to be used later when calling perm_set($filename, $perms).
perm_set($filename, $perms) β sets file permissions and owner of $filename according to $perms, which was previously acquired by calling perm_get($filename).
sysrun($cmd) β runs a shell command via system() and die()s if it fails. π Also works with a list of arguments, which are then interpreted as program name plus arguments, just like system() does it.
hammer($cmd, $arg, ...) β runs a command in the shell and simulates a user hammering the ENTER key to accept defaults on prompts. π¨β¨ (the vibes are "just say yes to everything", which is very on brand)
say($text, ...) β alias for print ..., "\n", just like Perl6 is going to provide it.
sudo_me() β checks if the current script is running as root. If yes, continue. If not, restart the current script with all command line arguments is restarted under sudo:
sudo scriptname args ...
Make sure to call this before any@ARGV-modifying functions likegetopts()have kicked in. Otherwise it's giving chaos.
bin_find($program) β searches all directories in $PATH (the ENV variable) for an executable named $program and returns the full path of the first hit. Returns undef if the program can't be found. π΅οΈββοΈ
fs_read_open($dir) β opens a file handle to read the output of the following process:
cd $dir; find ./ -xdev -print0 | cpio -o0 |
This can be used to capture a file system structure. ποΈ
fs_write_open($dir) β opens a file handle to write to a
| (cd $dir; cpio -i0)
process to restore a file system structure. To be used in conjunction with fs_read_open. π«Ά
pipe_copy($in, $out, [$bufsize]) β reads from $in and writes to $out, using sysread and syswrite. The buffer size used defaults to 4096, but can be set explicitly. πΈ
snip($data, $maxlen) β formats the data string in $data so that it's only (roughly) $maxlen characters long and only contains printable characters.
If $data is longer than $maxlen, it will be formatted like
(22)[abcdef[snip=11]stuvw]
indicating the length of the original string, the beginning, the end, and the number of 'snipped' characters.
If $data is shorter than $maxlen, it will be returned unmodified (except for unprintable characters replaced, see below).
If $data contains unprintable character's they are replaced by "." (the dot).
password_read($prompt, $opts) β reads in a password to be typed in by the user in noecho mode. πΆοΈ A call to password_read("password: ") results in
password: ***** (stars aren't actually displayed)
This function will switch the terminal back into normal mode after the user hits the 'Return' key.
If the optional $opts hash has { tty => 1 } set, then the prompt will be redirected to the console instead of STDOUT. π
nice_time($time) β formats the time in a human-readable way, less wasteful than the 'scalar localtime' formatting.
print nice_time(), "\n";
# 2007/04/01 10:51:24
It uses the system time by default, but it can also accept epoch seconds:
print nice_time(1170000000), "\n";
# 2007/01/28 08:00:00
It uses localtime() under the hood, so the outcome of the above will depend on your local time zone setting. π¦ (time zones are the main character, always)
def_or($foo, $default) β Perl-5.9 added the //= construct, which helps assigning values to undefined variables. Instead of writing
if(!defined $foo) {
$foo = $default;
}
you can just write
$foo //= $default;
However, this is not available on older perl versions (although there's source filter solutions). Often, people use
$foo ||= $default;
instead which is wrong if $foo contains a value that evaluates as false. π¬ So Sysadm::Install, the everything-and-the-kitchen-sink under the CPAN modules, provides the function def_or() which can be used like
def_or($foo, $default);
to accomplish the same as
$foo //= $default;
How does it work, how does $foo get a different value, although it's apparently passed in by value? Modifying $_[0] within the subroutine is an old Perl trick to do exactly that. π§ iykyk
is_utf8_data($data) β checks if the given string has the utf8 flag turned on. Works just like Encode.pm's is_utf8() function, except that it silently returns a false if Encode isn't available, for example when an ancient perl without proper utf8 support is used. β
utf8_check($data) β checks if we're using a perl with proper utf8 support, by verifying the Encode.pm module is available for loading. π
home_dir() β returns the path to the home directory of the current user. π π
β¨ AUTHOR β¨
Mike Schilli, <m@perlmeister.com>
β¨ COPYRIGHT AND LICENSE β¨
Copyright (C) 2004-2007 by Mike Schilli
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.3 or, at your option, any later version of Perl 5 you may have available.
okay bestie that's the whole thing π this page is from perl v5.34.0, dated 2022-06-17, and it's the Sysadm::Install(3pm) man page β go forth and install things responsibly π
β¨π«Ά
π¦ where this page comes from
- debian bookworm: libsysadm-install-perl 0.48-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libsysadm-install-perl 0.48-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libsysadm-install-perl 0.48-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libsysadm-install-perl 0.48-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libsysadm-install-perl 0.48-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms