Variables
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
name="Kai" # NO spaces around =
echo "$name" # reading it — with $
echo "${name}_backup" # curly braces separate the name from the text: Kai_backup
name = "Kai" (with spaces) is an error: the shell decides you're running the command name with the arguments = and Kai.
Always put variables in quotes: "$file". Without quotes a value with a space falls apart into several arguments: the file my notes.txt turns into my and notes.txt.
A command's result — into a variable:
today=$(date +%Y-%m-%d)
count=$(ls | wc -l)
Reading input:
read name # one whole line
read first last # words into variables
Environment variables are visible to the programs you start: HOME, USER, PATH, PWD. Your own are made like this: export API_KEY=....
Useful substitutions:
${name:-guest} # a default value if it's empty
${#name} # the length of the string
${file%.txt} # cut off the .txt ending
${path##*/} # everything after the last / (the file name)
Task. Read a first and a last name on one line. Print the greeting Hello, First Last! and the length of the first name: The first name has N letters. The input names are in Latin letters.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.