Tag: strings

  • Vars expansion

    Some examples of how to work with variables in bash.

    ### Vars expansion with ${} ###

    ## Default value
    # If a variable is not set a default value will be used. If it's set,
    # its value is used
    echo ${NAME:-Pepe}
    # -> Pepe
    NAME="Juanje"
    echo ${NAME:-Pepe}
    # -> Juanje

    ## Assign a default value
    # Assign a value to a var, only if it already has one
    NAME=""
    echo $NAME
    # ->
    echo ${NAME:=Pepe}
    # -> Pepe
    echo $NAME
    # -> Pepe
    echo ${NAME:=Juanje}
    # -> Pepe

    ## Show an error if variable does not exist (some vars exists but are empty)
    # you can set a customized message
    echo ${X?}
    # -> -bash: X: parameter null or not set
    echo ${X?La variable X no exite}
    # -> -bash: X: La variable X no exite
    X=""
    echo ${X?La variable X no exite}
    # ->
    X="Algo"
    echo ${X?La variable X no exite}
    # -> Algo

    ## Use an alternative value, if var already exists and has a value
    echo ${Y:+Alternative value}
    # ->
    Y=""
    echo ${Y:+Alternative value}
    # ->
    Y="Some value"
    echo ${Y:+Alternative value}
    # -> Alternative value

    ## Substrings
    # :{start}:{size}
    # If no size specified, a substring from {start}, to end
    # first char is 0
    TEXT="Un texto de ejemplo"
    echo ${TEXT:3}
    # -> texto de ejemplo
    echo ${TEXT:3:5}
    # -> texto

    ## Substring substracting from beginning
    # With one # first ocurrence of what comes after # will be substracted
    B="blablabla..."
    echo ${B#bla}
    # -> blabla...
    echo ${B#*bla}
    # -> blabla...
    # With 2 # longer strings will be substracted
    echo ${B##bla}
    # -> blabla...
    echo ${B##*bla}
    # -> ...
    # Another example:
    D="/srv/chroot/var/chroot/etc/apache"
    echo ${D#*chroot}
    # -> /var/chroot/etc/apache
    echo ${D##*chroot}
    # -> /etc/apache

    ## Substring from end
    # With one % first ocurrence of what comes after # will be substracted
    B="blablabla...blablabla"
    echo ${B%bla}
    # -> blablabla...blabla
    echo ${B%bla*}
    # -> blablabla...blabla
    # With 2 % longer strings will be substracted
    echo ${B%%bla}
    # -> blablabla...blabla
    echo ${B%%bla*}
    # ->
    # Example:
    D="/srv/chroot/var/chroot/etc/apache"
    echo ${D%chroot*}
    # -> /srv/chroot/var/
    echo ${D%%chroot*}
    # -> /srv/

    ## Variables names starting with a prefix
    echo ${!U*}
    # -> UID USER
    echo ${!B*}
    # -> B BASH BASH_VERSINFO BASH_VERSION
    echo ${!BASH*}
    # -> BASH BASH_VERSINFO BASH_VERSION

    ## Number of chars of variable value
    X="Un texto cualquiera"
    echo ${#X}
    # -> 19
    N=22435
    echo ${#N}
    # -> 5

    # Sustituir una cadena
    a=/etc/kung/foo
    echo ${a/foo/fu}
    # -> /etc/kung/fu