bash FAQ in sgml, html , ps. 

Newsgroups: comp.unix.shell

I have translated the bash FAQ in plain text to sgml. This translation has been made (semi) automatiquly, so it's not perfect, but it seems good enough.

You could find it at this adress: http://apodeline.free.fr/FAQ/bashFAQ/bash.sgml

http://apodeline.free.fr/FAQ/bashFAQ/bash.ps

http://apodeline.free.fr/FAQ/bashFAQ/bash.html

charles vidal

documented on: 2000.02.29 Tue 14:07:38

Meaning of special keys on the console 

^l = clear screen
^c = clear line
^m = enter
^o = enter
^j = enter
^a = go to beginning of line
^e = go to end of line
^d = delete char under cursor ( delete forwards )
^h = delete char defore cursor ( delete backwards )
^8 = delete char defore cursor ( delete backwards )
^w = delete from char before cursor till beginnng of this word
^u = delete from char before cursor till beginnng of line
^k = delete from char under cursor till end of line
^7 = undo
^p = arrow up ( previous )
^n = arrow down ( next )
^b = arrow left  ( back )
^f = arrow right ( forward )
^t = exchange two chars before cursor
^r = search in bash history
^q = clear input buffer in case someting is broken !

^^ in bash 

*Tags*: bash ^^

bash$ echo aaa bbb ccc ddd | xargs1 | sort -r
ddd
ccc
bbb
aaa
bash$ ^aaa^111^
echo 111 bbb ccc ddd | xargs1 | sort -r
ddd
ccc
bbb
111
  -- how to replace
bash$ ^xargs1^xargs -n 1^
echo 111 bbb ccc ddd | xargs -n 1 | sort -r
ddd
ccc
bbb
111

*N*:

For replacement,

Symptom 

bash$ echo 111 bbb ccc ddd | xargs -n 1 | sort -r | less
bash$  ^less^cat^
bash: ^less^cat^: command not found

Conclusion / Solution 

^ should be the 1st char!, no blank allowed!!!

documented on: 2000.09.05 Tue 13:58:55

cmd:alias 

Use alias everywhere 

Symptom 

Can't use var-held alias as pipe command:

$ alias alias_tst
alias alias_tst=echo
ChkCmd=alias_tst
ls *.rpm | $ChkCmd
-bash: alias_tst: command not found

Solution 

Use eval.

ls *.rpm | eval $ChkCmd

alias expansion 

Situation 

when an alias will be expand and when not?

Conclusion 

Analysis 

$ alias ls='ls --color=auto '
$ alias dir='ls -lF '
$ alias
alias dir='ls -lF '
alias ls='ls --color=auto '

— alias ls in alias dir is not expanded.

$ lf(){ dir "$@" | grep -v '^[dl]' ;}
$ type lf
lf is a function
lf ()
{
    ls --color=auto -lF "$@" | grep -v '^[dl]'
}

— alias dir in function lf is fully expanded.

documented on: 1999.12.03 Fri 14:12:03

Suspending and resuming a command 

If you did i.e. a "telnet" to another host, but want to do a "ls -l" on the current host, you do not have to close the "telnet" session.

Just type "^Z" (control-z) to suspend the current telnet session. The command is then waiting for you to resume. In this time you get a shell prompt and can issue any command.

If you are ready to continue, you can resume the "telnet" session with the command "fg %1" ("foreground: the first command waiting").

If you want to run the command in the background, you could issue a "bg %1" ("background: first command waiting"), too.

The command "jobs" lists all commands waiting.

{} in bash 

*Tags*: bash {}

$ echo aa{a,b}
aaa aab
echo mkdir -p /mnt/iso{1,2,3,4,5}
echo mkdir -p /mnt/tmp{,1,2}
echo mkdir -p /dos/drv_{a,b,c}{1,2,3,4}

no any space allowed 

bash$ echo m{1,2,3} n{1,2,3}
m1 m2 m3 n1 n2 n3
bash$ echo m{1,2,3 a b} n{1,2,3}
m{1,2,3 a b} n1 n2 n3
bash$ echo m{1,2,3,a,b} n{1,2,3}
m1 m2 m3 ma mb n1 n2 n3
bash$ echo m{1,2,3,a, b}
m{1,2,3,a, b}

bash arg completion 

http://enterprise.linux.com/article.pl?sid=05/09/14/2135236&tid=89

bash can complete args from your history using M-TAB (dynamic-complete-history) or alt-TAB

for example, type

$ echo fjdslkfjdslk

then try

$ printf fj M-TAB

in console. if this doesn't work try putting

M-TAB: dynamic-complete-history

in your .inputrc

bash can also complete variable names echo $P TAB TAB

By Anonymous Reader on 2005.09.19

cmd:bash history usage 

Usage 

$ /bin/echo a1 b2 c3 d4
a1 b2 c3 d4
pick some word 
$  echo !:0
 echo /bin/echo
/bin/echo
$  echo !:1
 echo a1
a1
$  echo !:2
 echo b2
b2
pick range of words 
$  echo !*
echo a1 b2 c3 d4
a1 b2 c3 d4

— all previous parameters

ls -f a1 b2 c3 d4 &
$ ls !:1-
ls -f a1 b2 c3 d4

— all previous parameters except last, best for & sign

$ echo A /a/b/c.d.e
A /a/b/c.d.e
$ echo B !:2*
echo B /a/b/c.d.e
/a/b/c.d.e

— omit some leading parameters

Help 

Event Designators
    An  event  designator  is  a reference to a command line entry in the
    history list.
!      Start a history substitution, except when followed by a blank,
       newline, = or (.
!!     Refer to the previous command.  This is a synonym for `!-1'.
!n     Refer to command line n.
!-n    Refer to the current command line minus n.
!string
       Refer to the most recent command starting with string.
!?string[?]
       Refer to the most recent command containing string.
^string1^string2^
       Quick   substitution.   Repeat  the  last  command,  replacing
       string1 with string2.  Equivalent to ``!!:s/string1/string2/''
       (see Modifiers below).
!#     The entire command line typed so far.
Word Designators
    A  :  separates the event specification from the word designator.  It
    can be omitted if the word designator begins with a ^, $,  *,  or  %.
    Words  are  numbered  from  the beginning of the line, with the first
    word being denoted by a 0 (zero).
0 (zero)
       The zeroth word.  For the shell, this is the command word.
n      The nth word.
^      The first argument.  That is, word 1.
$      The last argument.
%      The word matched by the most recent `?string?' search.
x-y    A range of words; `-y' abbreviates `0-y'.
*      All of the words but the zeroth.  This is a synonym for `1-$'.
       It  is  not an error to use * if there is just one word in the
       event; the empty string is returned in that case.
x*     Abbreviates x-$.
x-     Abbreviates x-$ like x*, but omits the last word.
Modifiers
    After the optional word designator, you can add a sequence of one  or
    more of the following modifiers, each preceded by a `:'.
h      Remove a trailing pathname component, leaving only the head.
r      Remove  a  trailing suffix of the form .xxx, leaving the basename.
e      Remove all but the trailing suffix.
t      Remove all leading pathname components, leaving the tail.
p      Print the new command but do not execute it.
q      Quote the substituted words, escaping further substitutions.
x      Quote the substituted words as with q, but break into words at
       blanks and newlines.
s/old/new/
       Substitute new for the first occurrence of old in the event
       line.  Any delimiter can be used in place of /.  The final
       delimiter is optional if it is the last character of the event
       line.  The delimiter may be quoted in old and new with a
       single backslash.  If & appears in new, it is replaced by old.
       A single backslash will quote the &.
&      Repeat the previous substitution.
g      Cause changes to be applied over the entire event line.   This
       is  used  in  conjunction  with `:s' (e.g., `:gs/old/new/') or
       `:&'.  If used with `:s', any delimiter can be used  in  place
       of  /,  and  the final delimiter is optional if it is the last
       character of the event line.

cmd:bash history help 

command_oriented_history
     If  set, bash attempts to save all lines of a multiple-line command in
     the same history entry.  This allows  easy  re-editing  of  multi-line
     commands.
previous-history (C-p)
       Fetch the previous command from the history list, moving back
       in the list.
next-history (C-n)
       Fetch the next command from the history list, moving  forward
       in the list.
beginning-of-history (M-<)
       Move to the first line in the history.
end-of-history (M->)
       Move  to  the  end  of the input history, i.e., the line cur-
       rently being entered.
reverse-search-history (C-r)
       Search backward starting at the current line and moving  `up'
       through  the  history  as  necessary.  This is an incremental
       search.
forward-search-history (C-s)
       Search forward starting at the current line and moving `down'
       through  the  history  as  necessary.  This is an incremental
       search.
non-incremental-reverse-search-history (M-p)
       Search backward through the history starting at  the  current
       line  using a non-incremental search for a string supplied by
       the user.
non-incremental-forward-search-history (M-n)
       Search forward through the history  using  a  non-incremental
       search for a string supplied by the user.
history-search-forward
       Search  forward through the history for the string of charac-
       ters between the start of the current line  and  the  current
       point.   This  is a non-incremental search.  By default, this
       command is unbound.
Note man from linux will format output according to the current window setting on the fly.

documented on: Sat 02-06-99 10:45:44

history -s arg [arg …] 

With no options, display the command history list with line numbers. Lines listed with a * have been modified. An argument of n lists only the last n lines. If filename is supplied, it is used as the name of the history file; if not, the value of HISTFILE is used. Options, if supplied, have the following meanings:

-a   Append the ``new'' history  lines  (history  lines
     entered  since  the  beginning of the current bash
     session) to the history file.
-n   Read the history lines not already read  from  the
     history file into the current history list.  These
     are lines appended to the history file  since  the
     beginning of the current bash session.
-r   Read the contents of the history file and use them
     as the current history.
-w   Write the current history  to  the  history  file,
     overwriting the history file's contents.
-c   Clear  the  history  list  by  deleting  all   the
     entries.

documented on: Wed 03-24-99 09:59:08

cmd:bash 

Editor commands (+)
    `bindkey'  lists  key  bindings and `bindkey -l' lists and
    briefly describes editor commands.  Only new or especially
    interesting  editor  commands  are  described  here.   See
    emacs(1) and vi(1) for descriptions of each  editor's  key
    bindings.
complete-word-fwd (not bound)
        Replaces  the  current word with the first word in
        the list of possible completions. May be  repeated
        to  step down through the list.  At the end of the
        list, beeps and reverts to the incomplete word.
expand-history (M-space)
        Expands history substitutions in the current word.
        See History substitution.  See  also  magic-space,
        toggle-literal-history  and  the  autoexpand shell
        variable.
expand-variables (^X-$)
        Expands the variable to the left  of  the  cursor.
        See Variable substitution.
history-search-backward (M-p, M-P)
        Searches  backwards through the history list for a
        command beginning with the current contents of the
        input  buffer  up to the cursor and copies it into
        the input buffer.  The  search  string  may  be  a
        glob-pattern  (see Filename substitution) contain-
        ing `*', `?', `[]' or `{}'.  up-history and  down-
        history will proceed from the appropriate point in
        the history list.  Emacs mode only.  See also his-
        tory-search-forward and i-search-back.
insert-last-word (M-_)
        Inserts the last word of the previous  input  line
        (`!$') into the input buffer.  See also copy-prev-
        word.
spell-line (M-$)
        Attempts to correct the spelling of each  word  in
        the  input  buffer,  like  spell-word, but ignores
        words whose first character is one  of  `-',  `!',
        `^'  or  `%', or which contain `\', `*' or `?', to
        avoid problems with  switches,  substitutions  and
        the like.  See Spelling correction.
spell-word (M-s, M-S)
        Attempts  to  correct  the spelling of the current
        word  as  described  under  Spelling   correction.
        Checks  each  component of a word which appears to
        be a pathname.
toggle-literal-history (M-r, M-R)
        Expands or `unexpands'  history  substitutions  in
        the input buffer.  See also expand-history and the
        autoexpand shell variable.
which-command (M-?)
        Does  a  which (see the description of the builtin
        command) on the first word of the input buffer.

*Tags*: history key,tcsh key bindings

host:~/bin>bindkey
Standard key bindings

"^L"           ->  clear-screen
"^R"           ->  redisplay

"^N"           ->  down-history
"^P"           ->  up-history

"^S"           ->  tty-stop-output
"^Q"           ->  tty-start-output

"^T"           ->  transpose-chars

"^U"           ->  kill-whole-line
"^Y"           ->  yank

"^[?"          -> which-command
"^[H"          -> run-help

"^[B"          -> backward-word
"^[D"          -> delete-word
"^[F"          -> forward-word

"^[C"          -> capitalize-word
"^[L"          -> downcase-word

"^[N"          -> history-search-forward
"^[P"          -> history-search-backward
"^[R"          -> toggle-literal-history

"^[S"          -> spell-word
"^[_"          -> insert-last-word

documented on: Sun 01-24-99 21:01:37

bash misc helps 

FIXME: this section needs clean up those duplicated info.

DIRSTACK
     An array variable (see  Arrays  below)  containing  the
     current  contents  of the directory stack.  Directories
     appear in the stack in the order they are displayed  by
     the  dirs  builtin.  Assigning to members of this array
     variable may be used to modify directories  already  in
     the stack, but the pushd and popd builtins must be used
     to add and  remove  directories.   Assignment  to  this
     variable  will  not  change  the current directory.  If
     DIRSTACK is unset, it  loses  its  special  properties,
     even if it is subsequently reset.
Arrays
   Bash provides one-dimensional array variables.  Any variable
   may be used as an array; the declare builtin will explicitly
   declare an array.  There is no maximum limit on the size  of
   an  array,  nor  any  requirement that members be indexed or
   assigned contiguously.  Arrays are  indexed  using  integers
   and are zero-based.
An  array  is  created  automatically  if  any  variable  is
assigned  to  using  the  syntax name[subscript]=value.  The
subscript is treated as an arithmetic expression  that  must
evaluate  to  a  number  greater  than or equal to zero.  To
explicitly declare an array, use declare -a name (see  SHELL
BUILTIN COMMANDS below).  declare -a name[subscript] is also
accepted; the  subscript  is  ignored.   Attributes  may  be
specified  for  an  array  variable  using  the  declare and
readonly builtins.  Each attribute applies to all members of
an array.
Arrays are assigned to using  compound  assignments  of  the
form  name=(value1  ...  valuen), where each value is of the
form [subscript]=string.  Only string is required.   If  the
optional  brackets and subscript are supplied, that index is
assigned to; otherwise the index of the element assigned  is
the  last  index  assigned  to  by  the  statement plus one.
Indexing starts at zero.  This syntax is  also  accepted  by
the  declare  builtin.   Individual  array  elements  may be
assigned to using the  name[subscript]=value  syntax  intro-
duced above.
Any  element  of  an   array   may   be   referenced   using
${name[subscript]}.   The  braces are required to avoid con-
flicts with pathname expansion.  If subscript is @ or *, the
word  expands  to  all  members  of  name.  These subscripts
differ only when the word appears within double quotes.   If
the  word  is  double-quoted, ${name[*]} expands to a single
word with the value of each array member  separated  by  the
first  character of the IFS special variable, and ${name[@]}
expands each element of name to a separate word.  When there
are  no  array members, ${name[@]} expands to nothing.  This
is analogous to the expansion of the  special  parameters  *
and  @  (see Special Parameters above).  ${#name[subscript]}
expands to the length of ${name[subscript]}.   If  subscript
is  *  or  @, the expansion is the number of elements in the
array.  Referencing an array variable without a subscript is
equivalent to referencing element zero.
HISTCONTROL
     If set to a value of  ignorespace,  lines  which  begin
     with  a  space character are not entered on the history
     list.  If set to a value of ignoredups, lines  matching
     the  last  history  line  are  not entered.  A value of
     ignoreboth combines the two options.
Brace Expansion
   For example, a{d,c,b}e expands into `ade ace  abe'.
     and,
        mkdir /usr/local/src/bash/{old,new,dist,bugs}
   or
        chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
Tilde Expansion
   If the tilde-prefix is a `~+', the value of the shell  vari-
   able  PWD replaces the tilde-prefix.  If the tilde-prefix is
   a `~-', the value of the shell variable  OLDPWD,  if  it  is
   set,  is substituted.  If the characters following the tilde
   in the tilde-prefix consist of a number N,  optionally  pre-
   fixed  by  a `+' or a `-', the tilde-prefix is replaced with
   the corresponding element from the directory  stack,  as  it
   would  be  displayed  by  the  dirs builtin invoked with the
   tilde-prefix as an argument.  If  the  characters  following
   the  tilde in the tilde-prefix consist of a number without a
   leading `+' or `-', `+' is assumed.
Arithmetic Expansion
   Arithmetic  expansion allows the evaluation of an arithmetic
   expression and the substitution of the result.   The  format
   for arithmetic expansion is:
        $((expression))
Readline Initialization
   Readline is customized by putting commands in an initializa-
   tion  file  (the  inputrc  file).   The name of this file is
   taken from the value of the INPUTRC variable.  If that vari-
   able  is  unset,  the default is ~/.inputrc.  When a program
   which uses the readline library starts up,  the  initializa-
   tion  file  is  read, and the key bindings and variables are
   set.  There are only a few basic constructs allowed  in  the
   readline  initialization  file.   Blank  lines  are ignored.
   Lines beginning with a # are comments.  Lines beginning with
   a $ indicate conditional constructs.  Other lines denote key
   bindings and variable settings.
The default key-bindings may  be  changed  with  an  inputrc
file.   Other  programs  that use this library may add their
own commands and bindings.
Readline Variables
   Readline has variables that can be used to further customize
   its  behavior.   A  variable  may be set in the inputrc file
   with a statement of the form
set variable-name value
Except where noted, readline variables can take  the  values
On or Off.  The variables and their default values are:
completion-ignore-case (Off)
     If set to On, readline performs filename  matching  and
     completion in a case-insensitive fashion.
completion-query-items (100)
     This determines when the user is queried about  viewing
     the  number  of  possible  completions generated by the
     possible-completions command.  It may  be  set  to  any
     integer  value  greater  than or equal to zero.  If the
     number of possible completions is greater than or equal
     to  the  value  of  this  variable,  the  user is asked
     whether or not he wishes to view them;  otherwise  they
     are simply listed on the terminal.
possible-command-completions (C-x !)
     List the possible completions of the text before point,
     treating it as a command name.
dynamic-complete-history (M-TAB)
     Attempt completion on the text before point,  comparing
     the text against lines from the history list for possi-
     ble completion matches.
show-all-if-ambiguous (Off)
     This alters the  default  behavior  of  the  completion
     functions.   If  set  to on, words which have more than
     one possible completion cause the matches to be  listed
     immediately instead of ringing the bell.
visible-stats (Off)
     If  set  to  On,  a character denoting a file's type as
     reported by stat(2) is appended to  the  filename  when
     listing possible completions.

bash invocation 

The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error.

When bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The —noprofile option may be used when the shell is started to inhibit this behavior.

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists.

When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

but the value of the PATH variable is not used to search for the file name.

If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. The —noprofile option may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the —rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any startup files. When invoked as sh, bash enters posix mode after the startup files are read.

documented on: Tue 02-23-99 20:41:42

Using aliases or functions in bash script 

Newsgroups: gmane.linux.debian.user
Date: Sat, 26 Jan 2008

An advanced bash alias expansion question — How can I use my aliases or functions in my bash script?

I have the following alias and function *already* defined in my ~/.bashrc:

$ bash
$ alias rd
alias rd='rmdir'
$ type dt
dt is a function
dt ()
{
    pushd +$1
}
$ exit
exit

I.e., there are there in the interactive shell. Now I want to use them in my script, How can I use them in my script?

Looking through the man pages, I think the following content is related to my question:

Aliases  are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt.
O [shopt_option] shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN COMMANDS below). If shopt_option is present, -O sets the value of that option; +O unsets it. If shopt_option is not supplied, the names and values of the shell options accepted by shopt are printed on the standard output. If the invocation option is +O, the output is displayed in a format that may be reused as input.
expand_aliases
        If set, aliases are expanded as  described  above  under
        ALIASES.  This option is enabled by default for interac-
        tive shells.

And this is what I've tried:

$ bash -c 'shopt -s expand_aliases; alias rd'
bash: line 0: alias: rd: not found
$ bash -O expand_aliases -c 'rd /tmp/ttt; alias rd; dt bin; type dt'
bash: rd: command not found
bash: line 0: alias: rd: not found
bash: dt: command not found
bash: line 0: type: dt: not found

I even tried the following but it didn't work either:

$ bash -O expand_aliases -c '. ~/.bashrc; (rd /tmp/ttt; alias rd; dt bin; type dt)'

Solution 

> Use functions. Don't use aliases.

This sounds like "Don't use #define in C" to me. Despite its limitations, why one can't use aliases in scripts?

xpt

Note: no answer.

Solution 

> An advanced bash alias expansion question --
> How can I use my aliases or functions in my bash script?
> PS. I even tried the following but it didn't work either:
>
>   $ bash -O expand_aliases -c '. ~/.bashrc; (rd /tmp/ttt; alias rd; dt bin; type dt)'
$ cat .bashrc
alias rd="echo foo"
$ bash -c 'alias rd'
bash: line 0: alias: rd: not found
$ bash -c '. ~/.bashrc; alias rd'
alias rd='echo foo'
$ bash -c '. ~/.bashrc; (alias rd)'
alias rd='echo foo'

As far as I can see, your last attempt should have worked.

The point of my previous response, which I complete failed to make (and in fact didn't realize until after I'd sent it…) is that your .bashrc probably includes a line of the form:

[ -z "$PS1" ] && return

So that the bashrc returns prior to defining any aliases. For example:

$ cat .bashrc
alias rd="echo foo"
$ bash -c '. ~/.bashrc; alias rd;'
alias rd='echo foo'
$ cat > .bashrc << 'EOF'
 > [ -z "$PS1" ] && return
 > alias rd="echo foo"
 > EOF
$ bash -c '. ~/.bashrc; alias rd;'
bash: line 0: alias: rd: not found
$ bash -c 'PS1="."; . ~/.bashrc; alias rd;'
alias rd='echo foo'

Another solution is to put the function and alias definitions before the check for the interactive shell. I think that a better solution is to define PS1 to fool the test as above, but I don't think that is a particularly good solution either. Probably better would be to move the function/alias definitions into a .bash_functions file, source that from .bashrc and from any scripts that want the functions and aliases.

William Pursell @gmail.com

Solution 

>> An advanced bash alias expansion question --
>> How can I use my aliases or functions in my bash script?
>
>> PS. I even tried the following but it didn't work either:
>>
>>   $ bash -O expand_aliases -c '. ~/.bashrc; (rd /tmp/ttt; alias rd; dt bin; type dt)'
>
> . . . your .bashrc probably includes a line of the form:
> [ -z "$PS1" ] && return
>
> So that the bashrc returns prior to defining any aliases. . .

OMG, that's EXACTLY the reason!

For NEARLY THREE YEARS[1] has the question been haunting me, and you solve it, by identifying my culprit line via looking through a crystal ball :-).

Thanks a million William!!!

[1] http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-06/0416.html

xpt

Solution 

Trying History 

The alias def and its usage should not be on the same line:

$ cat test.sh
. ~/bin/.aliases_bs; alias rd; shopt -s expand_aliases; rd -v /tmp/ttt
$ bash test.sh
alias rd='rmdir'
test.sh: line 1: rd: command not found

'alias rd' shows that the alias has been defined, but invocating it still fails.

$ cat test.sh
. ~/bin/.aliases_bs; alias rd
rd -v /tmp/ttt
$ bash test.sh
alias rd='rmdir'
rmdir: removing directory, /tmp/ttt

— Putting the alias def and its usage on different line solved the problem.

But better yet, use BASH_ENV, especially when using the bash commandline:

mkdir /tmp/ttt
$ BASH_ENV=~/bin/.aliases_bs bash -c "rd -v /tmp/ttt"
rmdir: removing directory, /tmp/ttt

documented on: 2008-01-27

using aliases in .bashrc 

*Tags*: :bash, :alias

> > It seems I can't use alias in .bashrc. To illustrate it, I put the
> > following 2 lines at the bottom of my .bashrc file:
> [...]
> Works fine on linux/hpux for both bash and bash2.
> [...]

Thanks Dan, which bash version are you using? I found that it might related with the bash version.

I put the following line to the top of my .bashrc file (which is going to be process before any other init scripts, right?)

alias bash_alias_test='echo just testing'; set -x; alias bash_alias_test
bash_alias_test; set +x; unalias bash_alias_test
if [ ${PS1:+T} ]; then
alias bash_alias_test='echo just testing'; set -x; alias bash_alias_test
bash_alias_test; set +x; unalias bash_alias_test
fi
alias bash_alias_test='echo just testing'; set -x; alias bash_alias_test
bash_alias_test; set +x; unalias bash_alias_test

and it works for one of my account that use bash 1.14.7. but for another account on the same machine which is using bash 2.04, I got:

+ alias bash_alias_test
alias bash_alias_test='echo just testing'
+ echo just testing
just testing
+ set +x
+ alias bash_alias_test
alias bash_alias_test='echo just testing'
+ bash_alias_test
bash: bash_alias_test: command not found
+ set +x
+ alias bash_alias_test
alias bash_alias_test='echo just testing'
+ echo just testing
just testing
+ set +x

So, can we conclude that bash 2.04 can no longer process alias defines in if clause now? Oh, I think now bash thinks if we define alias in if clause, it can only be used after the if statement.

bash ^d 

Newsgroups: comp.os.linux.misc,comp.unix.questions
>In Linux slackware, when I try to use ^d to logout from bash, I got
>a warning saying something like "type logout instead". How can I
>disable this feature?

Shell Variables …

IGNOREEOF
     Controls the action of the shell on receipt of  an  EOF
     character  as the sole input.  If set, the value is the
     number of consecutive EOF characters typed as the first
     characters  on an input line before bash exits.  If the
     variable exists but does not have a numeric  value,  or
     has  no value, the default value is 10.  If it does not
     exist, EOF signifies the end of  input  to  the  shell.
     This is only in effect for interactive shells.

Barry Margolin

documented on: 2001.01.08 Mon 18:13:12

how bash encode/decode characters with byte value greater than 0x7f 

Newsgroups:  gmane.linux.debian.user
Date:        Thu, 16 Nov 2006 11:59:59 -0500
> For characters whose byte values are greater than 0x7f, how bash
> encode/decode them?
>
> I.e.,
>
>  echo $'\312\325\274\376\317\344' | bash_encode
>
> Anybody know how to make the output similar to '\312\325\274\376\317\344'?

Just FYI,

$ echo $'\312\325\274\376\317\344' | od -b 0000000 312 325 274 376 317 344 012

T

The new x-window behavior on xterm title 

I used to set my own xterm titles, but after the recent upgrade of my Debian, the title of my xterm and rxvt are changed (to uid@host:/pwd), which I don't like.

How can I go back and use my own xterm titles?

I think this is a x-window level of change, because, I verified that the rxvt package is not updated, though its behavior is the same as xterm, i.e., same thing happens to rxvt while it is not updated.

Further test reveals that, I can't even use the

echo -ne "\033]0;aaaa\007"

to set my xterm title, while

echo -ne "\033]0;aaaa\007"; cat

will work as long as I don't ^d out from the cat. Further, it has nothing to do with my PS1. I've changed it to simply

PS1="\n\\$ "

and it didn't solved the problem.

The new x-window behavior on xterm title 

On Tue, 21 Jun 2005 15:49:10 -0400, Bill Marcum wrote:

> > Further test reveals that, I can't even use the
> >
> > echo -ne "\033]0;aaaa\007"
> >
> > to set my xterm title
> >
> Look for PROMPT_COMMAND in /etc/bash.bashrc

Thanks! that's the culprit.

$ grep PROMPT_COMMAND /etc/bash.bashrc
   PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

T

Clear keyboard input buffer in Bourne shell 

Newsgroups: comp.unix.shell
>extraneous characters are generated -- and they end up in the keyboard's
>input buffer, so that the next prompt the user sees has these characters
>present (though ...

I'll stick to some generic advice on the subject:

Some systems have a stty command which supports a "flushi" and/or a "flush" option, in which case you can use that.

Otherwise you probably will need to resort to compiling this "flushi" program:

#include <unistd.h>
#include <termios.h>
int main(void) { tcflush(STDIN_FILENO, TCIFLUSH); return 0; }

Some other, more kludgy solutions:

Ken Pizzini

Any interactive debugger for bash scripts? 

Newsgroups: comp.unix.shell
> I'm trying to find a way to do interactive debugging of bash shell
> scripts; has anybody any suggestion?

ftp://ftp.ora.com/published/oreilly/nutshell/bash/bash2examples.tar.gz

and the subdirectory "debugger" of the tarfile. It is described in Chapter 9 of O'Reilly's "Learning the bash shell", 2nd edition.

Boudewijn Moonen

multi-dimensionable arrays in bash 

>Could someone guide me around bash's lack of support for
>multi-dimensional arrays?  I've tried creating one array with the name
>of the other arrys.  Here is  a sample of what I'm trying to do:
>#!/bin/sh
>
>SERVER="MACSERVER ADVMKT CIRFIN OPSHR MIS1"
>
>MACSERVER="1 2 3 4 5"
>ADVMKT="6 7 8 9 10"
>CIRFIN="11 12 13 14 15"
>OPSHR="16 17 18 19 20"
>MIS1="21 22 23 24 25"
>
>for SYSTEM in ${SERVER}
>do
>    echo "System: "${SYSTEM}
>    for ITEM in ${SYSTEM}
>    do
>        echo "Item: "${ITEM}
>    done
>done

The "for ITEM" loop is iterating over the (single) value In bash this is easy --- use "indirect expansion":

for ITEM in ${!SYSTEM}

Ken Pizzini

multi-dimensionable arrays in bash 

Indirect substitution first appeared with bash-2.0. Earlier versions did not have it.

Chet Ramey

"rehash" for bash? 

>I know I don't need to do a rehash for bash, if new comands appear, it
>get picked up automatically.
>
>But strange thing is that if I launch an application then create an
>instance in my local bin, which comes first in my $PATH, and issue the
>command again, bash still pick the application from the old place, not
>the new place:

You don't need to rehash to find new commands, but if the location of a command that has already been hashed has changed you need to tell the shell so that it will update its hash. You can use "hash <command>" to update the hash for that command, or "hash -r" to forget all hashed commands and start fresh.

The whole point of the hash is to avoid checking all the directories in your PATH every time you type a command

Barry Margolin,

documented on: 1999.10.05 Tue 10:46:12

bash alias doesn't accept $1 

$1 doesn't work in bash alias:

$ alias test_p='echo 1:$1 2:$2 3:$3'
$ test_p sss ww bbb
1: 2: 3: sss ww bbb

bash alias that mask original command 

>say I name an alias sh and in it I want to use the original sh command.
>How can I do it in bash?

First, use a shell function. Then use something like

sh()
{
        command sh "$@"
}

or

cd()
{
        builtin cd "$@" && echo $PWD
}

If you absolutely must use an alias, you can use the `command' or `builtin' builtins within the alias:

alias sh="command sh"
alias cd="builtin cd"

but if you want to do anything even moderately complex, you should use a shell function.

As a special case, bash checks the first word of an alias to see whether or not it is the same as the alias being expanded, and will not do recursive alias expansion if it is, so you could even do without the `command' and `builtin' in the above aliases.

Chet

paste tab to bash 

>I don't know why I can't paste tab into bash.
>
>The following line:
>
>texts1         # 2 tabs before it
>
>when pasted into bash, lookes like:
>
>texts1# 2 tabs before it.
>
>The 2 (whatever) tabs disapeared.

When you're pasting into a terminal window, the pasted text looks just like ordinary keyboard input. In bash, TAB is the filename completion character by default, not a literal input character. When typing interactively you can enter a literal TAB with C-v TAB, but I don't know offhand of a way to make pasting automatically insert C-v's before each TAB. You'll have to unbind the TAB key first.

sh and csh don't do filename completion (csh has filename completion, but you have to do "set filec" to turn it on), so the TAB is taken as a literal input.

Barry Margolin

paste tab to bash 

> I don't know offhand of a way to make pasting automatically insert C-v's
> before each TAB.

oh, I was testing my script interactively in bash, which involes heredoc "expand <<". Knowing above, I changed my method of pasting the whole codes. Instead, I omitted the heredoc part and paste right to the expand.

Thus my tab is not interepreted by bash any more. thanks!

String comparison in bash 

Date: 9 Sep 2002 04:17:09 GMT
Newsgroups: comp.os.linux.misc
 > Bash manual says ">" and "<" can compare strings based on lexicography
order.
When used within [[ ]], not [ ].
> But:
>
> bash2.05>if [ "1.4" > "1.3" ]; then echo "okay"; fi
> okay
$ if [[ "1.4" > "1.3" ]]; then echo "okay"; fi
okay
> bash2.05>if [ "1.4" < "1.3" ]; then echo "okay"; fi
> okay
$ if [[ "1.4" < "1.3" ]]; then echo "okay"; else echo NOT; fi
NOT

Get the alias definition 

Newsgroups: comp.unix.shell
Date: 27 Sep 2001 11:37:16 -0300

Aliases help me in my daily life. One problem is that they can't be used as xargs parameters, i.e.

xargs some_alias_command rest of parameters

will not work. I'm trying to solve this generically by a wrapper function:

xargs `get_alias_def some_alias_command` rest of parameters

But so far I haven't find an elegant solution yet:

$ alias atest="echo 'aa bb'"
$ alias atest
alias atest='echo '\''aa bb'\'''
$ alias atest | cut -d= -f 2
'echo '\''aa bb'\'''
$ echo `!!`
echo `alias atest | cut -d= -f 2`
'echo '\''aa bb'\'''

See? the single quote is still there. How can I get:

$ echo 'echo '\''aa bb'\'''
echo 'aa bb'

Get the alias definition 

>  xargs `get_alias_def some_alias_command` rest of parameters

Personally, I don't recommend using aliases for anything but interactive use, and then only sparingly. Really, an aliases major benefit is the ability to override builtin behavior - for instance, redefining cd. Overuse of aliases can lead to confusion, whereas use of aliases in scripts can lead to indeterminate behavior. What you are trying to do you can only do if you first alias xargs:

$ mkdir test
$ cd test
$ >a;>b;>c
$ alias xx='ls -ld'
$ alias xargs='\xargs '
$ echo * | xargs xx
-rw-rw-rw-   1 dam        users            0 Sep 28 09:35 a
-rw-rw-rw-   1 dam        users            0 Sep 28 09:35 b
-rw-rw-rw-   1 dam        users            0 Sep 28 09:35 c

Note that the alias for xargs is self-referencing. You must escape the self-reference in some fashion, by either using a quoting syntax as with the backslash, as above, or by designating the full path name. Also note the alias ends with a space. Normally, alias substitution is only done on the first word in a statement. However, if that first word is an alias and the alias ends in a space, the next word is checked for aliases. If that alias ends with a space, the next word is checked and so on.

This can lead to some confusing behavior, particularly with aliases of cd.

$ cd /opt
$ ls -l
drwxr-xr-x           ...     applix
...
$ cd applix
pd[4]: /opt/applix/applix: not a directory

Dan Mercer

Get the alias definition 

$ alias xargs1="xargs -l1"
$ echo * | xargs1 xx
xargs: xx: No such file or directory
$ alias xargs1="xargs -l1 "
$ echo * | xargs1 xx
-rw-rw----    1 tong     tong          118 Sep 18 22:56 Changes
-rw-rw----    1 tong     tong           46 Sep 18 22:56 MANIFEST
...

Get the alias definition 

You could use such a function:

xargs_with_alias() {
  alias_name=$1
  shift
  eval expanded_alias="`alias $alias_name | cut -d = -f2-`"
  eval xargs "$expanded_alias" '"$@"'
}

Stephane

Get the alias definition 

> >   eval xargs "$expanded_alias" '"$@"'
>
> Anybody else can come up with more generic solutions that don't
> tie up with xargs? I just use xargs as an example to explain the
> situation... thanks

What do you call a generic solution?

Maybe

expand_alias xargs -n 1 '[|' alias_name '|]' foo bar
(every argument between '[|' and '|]' is considered an alias and is
expanded):

expand_alias() {
  typeset -i n=1
  command=
  while (( n <= $# )); do
    if eval "[[ \$$n = '[|' \
              && $(( n + 2 )) -le $# \
              && \$$((n + 2)) = '|]' ]]"; then
      eval "alias_name=\$$((n + 1))"
      eval expanded_alias="`alias $alias_name | cut -d = -f2-`"
      command="$command $expanded_alias"
      n=n+3
    else
      command="$command \"\$$n\""
      n=n+1
    fi
  done
  eval "$command"
}

Not much tested.

Stephane

documented on: Tue 11-10-98 11:23:13

poor man's wget 

Newsgroups: comp.unix.shell

I only now discovered the special handling of redirections to /dev/tcp/host/port introduced with Bash 2.x, and I like this small contruct which requests the main page from a web server:

{ echo "GET /" >&0; cat; } <>/dev/tcp/www.server.com/80

Also the first time a "<>" redirection is useful for me … ;-)

Martin Ramsch

Expect implementation entirely in bash 

Newsgroups: comp.unix.shell,alt.comp.lang.shell.unix.bourne-bash,gnu.bash Date: 15 Oct 2005 18:53:22 -0700

A friend of mine was trying to drive a scripted telnet session using bash, and did not have tools like Perl, Tcl/Tk or expect available on the platform, so I wrote a bash function to implement "expect" functionality directly, taking advantage of bash's "/dev/tcp" feature. Below is the function, which expects the global "timeout" variable to be initialized, and expects file descriptor #3 to already be open for reading and writing.

After the function is a usage example that works with my CMC system (see http://gangplank.org/ for more information on the system) — since my server implements telnet and doesn't provide the login prompt until the telnet protocol initialization completes, I have it wait for a \377 byte that indicates the start of the telnet protocol sequence. A similar technique could be used to send a telnet protocol response string for a known initial protocol sequence.

Also straightforward would be using the 3-digit codes in a protocol such as SMTP with this function to send an email, or to implement other such protocols.

Deven

#!/bin/bash

timeout=600

expect() {
   local expect="$1" send="$2"
   local delim="${expect:(-1):1}"
   local buffer="" block=""
   while read -u3 -r -t$timeout -d "$delim" block; do
      buffer="$buffer$block$delim"
      case "$buffer" in
         *"$expect")
            echo "$send" 1>&3
            return
            ;;
      esac
   done
}

exec 3<>/dev/tcp/localhost/9999
expect "`echo -en '\377'`" "guest"
expect "name:" "testing"
expect "blurb:" "testing2"

Deven T. Corzine