How can i run bash shell script in a posix environment? - bash

I was trying to run a bash shell script in ESXi shell.
Think ESXi is posix compatible, posix compiler threw much syntax errors.
please let me know if anyone has the answer

The manual lists the changed behavior when running in POSIX mode. You should adapt your script accordingly.
The following list is what’s changed when POSIX mode is in effect:
When a command in the hash table no longer exists, Bash will re-search $PATH to find the new location. This is also available with ‘shopt -s checkhash’.
The message printed by the job control code and builtins when a job exits with a non-zero status is ‘Done(status)’.
The message printed by the job control code and builtins when a job is stopped is ‘Stopped(signame)’, where signame is, for example, SIGTSTP.
The bg builtin uses the required format to describe each job placed in the background, which does not include an indication of whether the job is the current or previous job.
Reserved words appearing in a context where reserved words are recognized do not undergo alias expansion.
The POSIX PS1 and PS2 expansions of ‘!’ to the history number and ‘!!’ to ‘!’ are enabled, and parameter expansion is performed on the values of PS1 and PS2 regardless of the setting of the promptvars option.
The POSIX startup files are executed ($ENV) rather than the normal Bash files.
Tilde expansion is only performed on assignments preceding a command name, rather than on all assignment statements on the line.
The default history file is ~/.sh_history (this is the default value of $HISTFILE).
The output of ‘kill -l’ prints all the signal names on a single line, separated by spaces, without the ‘SIG’ prefix.
The kill builtin does not accept signal names with a ‘SIG’ prefix.
Non-interactive shells exit if filename in . filename is not found.
Non-interactive shells exit if a syntax error in an arithmetic expansion results in an invalid expression.
Non-interactive shells exit if there is a syntax error in a script read with the . or source builtins, or in a string processed by the eval builtin.
Redirection operators do not perform filename expansion on the word in the redirection unless the shell is interactive.
Redirection operators do not perform word splitting on the word in the redirection.
Function names must be valid shell names. That is, they may not contain characters other than letters, digits, and underscores, and may not start with a digit. Declaring a function with an invalid name causes a fatal syntax error in non-interactive shells.
POSIX special builtins are found before shell functions during command lookup.
The time reserved word may be used by itself as a command. When used in this way, it displays timing statistics for the shell and its completed children. The TIMEFORMAT variable controls the format of the timing information.
When parsing and expanding a ${...} expansion that appears within double quotes, single quotes are no longer special and cannot be used to quote a closing brace or other special character, unless the operator is one of those defined to perform pattern removal. In this case, they do not have to appear as matched pairs.
The parser does not recognize time as a reserved word if the next token begins with a ‘-’.
If a POSIX special builtin returns an error status, a non-interactive shell exits. The fatal errors are those listed in the POSIX standard, and include things like passing incorrect options, redirection errors, variable assignment errors for assignments preceding the command name, and so on.
A non-interactive shell exits with an error status if a variable assignment error occurs when no command name follows the assignment statements. A variable assignment error occurs, for example, when trying to assign a value to a readonly variable.
A non-interactive shell exists with an error status if a variable assignment error occurs in an assignment statement preceding a special builtin, but not with any other simple command.
A non-interactive shell exits with an error status if the iteration variable in a for statement or the selection variable in a select statement is a readonly variable.
Process substitution is not available.
Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes.
Assignment statements preceding shell function calls persist in the shell environment after the function returns, as if a POSIX special builtin command had been executed.
The export and readonly builtin commands display their output in the format required by POSIX.
The trap builtin displays signal names without the leading SIG.
The trap builtin doesn’t check the first argument for a possible signal specification and revert the signal handling to the original disposition if it is, unless that argument consists solely of digits and is a valid signal number. If users want to reset the handler for a given signal to the original disposition, they should use ‘-’ as the first argument.
The . and source builtins do not search the current directory for the filename argument if it is not found by searching PATH.
Subshells spawned to execute command substitutions inherit the value of the -e option from the parent shell. When not in POSIX mode, Bash clears the -e option in such subshells.
Alias expansion is always enabled, even in non-interactive shells.
When the alias builtin displays alias definitions, it does not display them with a leading ‘alias ’ unless the -p option is supplied.
When the set builtin is invoked without options, it does not display shell function names and definitions.
When the set builtin is invoked without options, it displays variable values without quotes, unless they contain shell metacharacters, even if the result contains nonprinting characters.
When the cd builtin is invoked in logical mode, and the pathname constructed from $PWD and the directory name supplied as an argument does not refer to an existing directory, cd will fail instead of falling back to physical mode.
The pwd builtin verifies that the value it prints is the same as the current directory, even if it is not asked to check the file system with the -P option.
When listing the history, the fc builtin does not include an indication of whether or not a history entry has been modified.
The default editor used by fc is ed.
The type and command builtins will not report a non-executable file as having been found, though the shell will attempt to execute such a file if it is the only so-named file found in $PATH.
The vi editing mode will invoke the vi editor directly when the ‘v’ command is run, instead of checking $VISUAL and $EDITOR.
When the xpg_echo option is enabled, Bash does not attempt to interpret any arguments to echo as options. Each argument is displayed, after escape characters are converted.
The ulimit builtin uses a block size of 512 bytes for the -c and -f options.
The arrival of SIGCHLD when a trap is set on SIGCHLD does not interrupt the wait builtin and cause it to return immediately. The trap command is run once for each child that exits.

Related

Read file and run command in zsh

So I generally create job files with a list of commands in it. Then I execute it like so
cat jobFile | while read a; do $a; done
Which always works in bash. However, I've just started working in Mac which apparently uses zsh. And this command fails with "no such file" etc. I've tested the job file by running few lines from it manually, so it should be fine.
I've found questions on zsh read inbut they tend to be reading in from variables e.g. $a=('a' 'b' 'c') or echo $a
Thank you for your answers!
In bash, unquoted parameter expansions always undergo word-splitting, so if a="foo bar", then $a expands to two words, foo and bar. As a command, this means running the command foo with an argument bar.
In zsh, parameter expansions to not undergo word-splitting by default, which means the same expansion $a would produce a single word foo bar, treated as the name of the command to execute.
In either case, relying on parameter expansion to "parse" a shell command is fragile; in addition to word-splitting, the expansion is subject to pathname expansion (globbing), and you are limited to simple commands and their arguments. No pipes, lists (&&, ||), or redirections allowed, as everything will be treated as the command name and a sequence of arguments.
What you want in both shells is to simply treat your job file as a shell script, which can be executed in the current shell using the . command:
. jobFile
Why are you executing it in such a cumbersome way? Assuming jobFile is a file holding a sequence of bash commands, you can simply run it as
bash jobFile
If it contains a sequence of zsh commands, you can likewise run it as
zsh jobFile
If you follow this approach, I would however reflect in the name of the job file, what shell it is intended for, i.e.
bash jobFile.bash
zsh jobFile.zsh
and, if you write a job file so that it is supposed to be compatible with either shell, I would name it jobFile.sh.

Where is "key=value bash-script" usage documented?

I often see key=value bash-script to pass variables to a bash script. Here is an example:
$ echo $0
-bash
$ cat foo.sh
#!/usr/bin/env bash
echo "key1: $key1"
$ key1=value1 ./foo.sh
key1: value1
I have checked Bash Reference Manual. But I can't a description related to this usage.
Section 3.7.4 "Environment"
The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.
Apparently the online version of the documentation fails to describe the syntax of a simple command completely. It reads:
3.2.1 Simple Commands
A simple command is the kind of command encountered most often. It’s just a sequence of words separated by blanks, terminated by one of the shell’s control operators (see Definitions). The first word generally specifies a command to be executed, with the rest of the words being that command’s arguments.
There is some information about the variable assignments that may precede a simple command on the section Simple Commands Expansion:
3.7.1 Simple Command Expansion
When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right.
The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing.
...
The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable.
The manual page bundled with the shell seems to be better at this. It says (the emphasis is mine):
Simple Commands
A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator.
You can always read the documentation of bash (and of any other CLI program installed on your computer) using man.
Type man bash on your terminal and use the usual keys (<spacebar>, b, /, q etc.) to navigate in the document. Behind the scenes, man uses your default pager program (which is, most probably, less) to put the information on screen.

What are the special dollar sign variables in zsh?

When using bash, there are self-referential variables that don't seem to be available in zsh. For example, $? gets the exit status of the most recent foreground process, $_ gets the last parameter of the previous command, etc.
Are there equivalents to these in zsh? I ask with reference to this question for bash.
bash calls these the special parameters (to distinguish them from ordinary variables and the positional parameters). zsh implements essentially the same set, but documents them along with other parameters set by the shell, though it does also tag each one as special.
See man zshparam:
PARAMETERS SET BY THE SHELL
In the parameter lists that follow, the mark `<S>' indicates that the
parameter is special. `<Z>' indicates that the parameter does not
exist when the shell initializes in sh or ksh emulation mode.
The following parameters are automatically set by the shell:
! <S> The process ID of the last command started in the background
with &, or put into the background with the bg builtin.
# <S> The number of positional parameters in decimal. Note that some
confusion may occur with the syntax $#param which substitutes
the length of param. Use ${#} to resolve ambiguities. In par-
ticular, the sequence `$#-...' in an arithmetic expression is
interpreted as the length of the parameter -, q.v.
ARGC <S> <Z>
Same as #.
$ <S> The process ID of this shell. Note that this indicates the
original shell started by invoking zsh; all processes forked
from the shells without executing a new program, such as sub-
shells started by (...), substitute the same value.
[... etc ...]

Why does `export` fail on bad substitutions but not command failures?

It’s well known that export masks the return value of command
substitutions in its variable assignments. But, interestingly,
export does not mask the return value of failed substitutions:
$ (set -eu; export FOO="$(bad_command)"); echo $?
bash: bad_command: command not found
0
$ (set -eu; export FOO="${bad_variable}"); echo $?
bash: bad_variable: unbound variable
1
$ (set -eu; export FOO="${}"); echo $? # bad substitution
bash: ${}: bad substitution
1
(Similar behavior in dash.)
What part of the specification indicates that failure of command
substitution does not propagate through export, but failure of
parameter expansion does?
Relevant sections from man bash (GNU Bash 4.4):
set -u
Treat unset variables and parameters other than the
special parameters "#" and "*" as an error when performing parameter
expansion. If expansion is attempted on an unset variable or
parameter, the shell prints an error message, and, if not interactive,
exits with a non-zero status.
and
export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the
environment of subsequently executed commands. If the -f option is
given, the names refer to functions. If no names are given, or if the
-p option is supplied, a list of names of all exported variables is
printed. The -n option causes the export property to be removed from
each name. If a variable name is followed by =word, the value of
the variable is set to word. export returns an exit status of 0
unless an invalid option is encountered, one of the names is not a
valid shell variable name, or -f is supplied with a name that is
not a function.
—I don’t see anything here that would distinguish between the two cases.
In particular, export just says that the value of the variable “is set
to” word, which suggests that it goes through the normal expansion
process (which it does) without special treatment.
POSIX specification references:
Shell Command Language
The export special builtin
The set special builtin
Neither case is really up to export
A command substitution just becomes text (empty or not) in a command's argument array. The Unix process model does not have any mechanism for relaying whether the text came from a program, or whether that program was successful.
This means that it's not possible to write an external command that behaves differently when you run foo var="$(true)" vs foo var="$(false)" vs foo var="" and shell builtins like export traditionally follow the same behavior for ease of implementation.
With set -u and unset variables, the command never runs at all. The shell simply skips execution if it encounters this condition while building the argument array, and reports failure instead. A command can't choose to ignore such a failure, since it's never consulted.
It would certainly be possible to implement a new shell mode that similarly skips execution and reports failure if command substitutions fail during the construction of the argument array, but this has not been a traditional feature so it's not in the POSIX spec.

What is the name of the $ or # signs that indicates if you're root?

I recently discovered that the # sign indicates that you're root on the shell (at least in a bash shell), and the $ sign indicates that you're not.
What is the name of this sign and does it really have the meaning that I give to it?
Is it only a bash thing?
Example with default bash configuration on Ubuntu:
john#mycomputer /tmp $ echo "I'm a simple user"
mycomputer /tmp # echo "I'm the root user"
There does not appear to be a formal definition of the prompt character indicating your privileges.
This thorough answer to “What is the origin of the UNIX $ (dollar) prompt?” provides lots of historical background, but it does not have a name for this indicator either.
In the absence of an official term, I'd call this the “prompt privilege indicator” or the “prompt indicator symbol” or even just “prompt indicator.”
All shells have a prompt whose default string ends in an indicator symbol, which (by default) almost always indicates whether you are root. Most shells allow you to change the prompt and most shells have a way to specify the prompt indicator symbol.
Here's what you can find in the various shell docs and standards:
A segment of the bash man page:
PROMPTING
When executing interactively, bash displays the primary prompt PS1 when
it is ready to read a command, and the secondary prompt PS2 when it
needs more input to complete a command. Bash displays PS0 after it
reads a command but before executing it. Bash allows these prompt
strings to be customized by inserting a number of backslash-escaped
special characters that are decoded as follows:
…
\$ if the effective UID is 0, a #, otherwise a $
From the zsh man pages:
Shell state
%# A `#' if the shell is running with privileges, a `%' if not.
Equivalent to `%(!.#.%%)'. The definition of `privileged', for
these purposes, is that either the effective user ID is zero,
or, if POSIX.1e capabilities are supported, that at least one
capability is raised in either the Effective or Inheritable
capability vectors.
The POSIX standard doesn't even specify what the privileged prompt symbol should be:
PS1
Each time an interactive shell is ready to read a command, the value of this variable shall be subjected to parameter expansion and written to standard error. The default value shall be $ . For users who have specific additional implementation-defined privileges, the default may be another, implementation-defined value.
See also the dash man page (dash is a popular basic POSIX shell, often installed as /bin/sh):
PS1 The primary prompt string, which defaults to ``$ '', unless you
are the superuser, in which case it defaults to ``# ''.
POSIX and dash don't have anything dynamic in what you can set $PS1 to. The default prompt is set once and is replaced by any assignments to the PS1 variable, losing the ability to distinguish between root and unprivileged users with a single character. You'd have to write your own code to determine if you're privileged and use its output in your PS1 assignment.
It's called a prompt. These days, they can be configured in many different ways. This related question gives some background.

Resources