Monday, April 8, 2013

Variable assignment and manipulation

CHECK IF VARIABLE IS SET:

${variable:-word} - If variable is not set, returns word, otherwise returns variable.
  • $ variable=bob
  • $ echo ${variable:-not set}
  • bob
  • $ unset variable
  • $ echo ${variable:-not set}
  • not set
${variable:=word} - If variable set, returns variable. If not set, assigns word to variable, then returns variable.
  • $ variable=bob
  • $ echo ${variable:=not set}
  • bob
  • $ unset variable
  • $ echo ${variable:=not set}
  • not set
  • $ echo ${variable}
  • not set
${variable:+word} - Returns word if variable isn't set. If variable is set, returns nothing
  • $ variable=bob
  • $ echo ${variable:+Variable already set}
  • Variable already set
  • $ unset variable
  • $ echo ${variable:+Variable already set}
  •  <this is the command returning nothing>
${variable:?word} - Return word if variable isn't set, and then terminate the shell with error.




  • $ variable=bob
  • $ echo ${variable:?word}
  • bob
  • $ unset variable
  • $ echo ${variable:?word}
  • bash: variable: word
${variable:?} - Return default error message if variable isn't set, and then terminate the shell with error.
  • $ variable=bob
  • $ echo ${variable:?word}
  • bob
  • $ unset variable
  • $ echo ${variable:?word}
  • bash: variable: parameter null or not set
 VARIABLE MANIPULATION

${variable:startnum} - Display variable starting at character startnum

  • $ variable=1234567890
  • $ echo ${variable:4}
  • 567890
${variable:startnum:length} - Display variable starting at character startnum, for total of length characters.
  • $ variable=1234567890
  • $ echo ${variable:4:2}
  • 56
${variable#pattern} - Finds the first and shortest instance of pattern, and removes it.
  • $ variable="landing ground on island"
  • $ echo ${variable#land*}
  • ing ground on island
${variable##pattern} - Finds the first and longest instance of pattern, and removes it.
  • $ variable="landing ground on island"
  • $ echo ${variable##land*}
  •  <this is the command returning nothing>
${variable%pattern} - Finds the last and shortest instance of pattern, and removes it.
  • $ variable="landing ground on island"
  • $ echo ${variable%*land}
  • landing ground on is
${variable%%pattern} - Finds the last and longest instance of pattern, and removes it.
  • $ variable="landing ground on island"
  • $ echo ${variable%%*land}
  •  <this is the command returning nothing>
${variable/pattern1/pattern2} - Replaces first instance of pattern1 with pattern2.
  • $ variable=1234554321
  • $ echo ${variable/1/00}
  • 00234554321
${variable//pattern1/pattern2} - Replaces all instances of pattern1 with pattern2.
  • $ variable=1234554321
  • $ echo ${variable//1/00}
  • 002345543200
${variable#pattern1/pattern2} - Replace pattern1 with pattern2 if variable begins with pattern1

${variable%pattern1/pattern2} - Replace pattern1 with pattern2 if variable ends with pattern1

No comments:

Post a Comment