דף קיצורים csh/tcsh

פוסט זה כולל טיפ קצר על כלי עבודה בסביבת Linux. בשביל ללמוד יותר על עבודה בסביבת Linux ו Unix אני ממליץ לכם לבדוק את קורס Linux שיש לנו כאן באתר. הקורס כולל מעל 50 שיעורי וידאו והמון תרגול מעשי ומתאים גם למתחילים.
 

הצורך לכתוב ולתחזק Shell Scripts משותף למתכנתים רבים. הנה אוסף קצר של קטעי tcsh שיעזרו לכם להזכר בסינטקס בפעם הבאה שתצטרכו לעבוד על סקריפט כזה.

אין בפוסט זה כל המלצה להשתמש ב csh, אלא הבעת אמפתיה אם זו הסביבה בה עליכם לעבוד. מומלץ גם לקרוא את המאמר המעולה ״הסיבות הטובות ביותר לא להשתמש ב csh״ או את המאמר הקצר יותר ״הפסיקו להשתמש ב csh״.

1. A first shell script

#!/usr/bin/env tcsh

# A shell script is just a text file that includes shell commands
# You'd usually type the shell name in the first line (called shbang)
# so shell knows which program the script is for,
# and grant it with executable permissions with:
# chmod +x <script_name>
# 
# BTW lines starting with hash are ignored by shell, except the first
# shbang line

echo "Hello Tcsh"

 

2. Command Line Arguments

#!/usr/bin/env tcsh

# $# is a special csh variable that holds all
# command line arguments passed to it
echo "Script started with: $# arguments"

# $1 refers to the first argument, $2 to the second
# $3 to the third and so on.

# To iterate all the arguments we use a while
# loop with shift.
# Each iteration removes the next argument
# and prints it

echo "Here they are:"
While ( $# > 0 )
    echo "Got: $1"
    shift
end

 

3. Standard Input

#!/Usr/bin/env tcsh

echo "Who are you?"

# The set command sets value in a variable,
# and the sepcial variable $< means the next input
# line. Note quoting the value to allow multiple words
set name="$<"

echo "Welcome, $name. Nice to see you"

 

4. Heredoc: Typing Message to a File

#!/Usr/bin/env tcsh

mkdir -p $1

# A heredoc allows typing text and running external commands
# to provide a "template" inside the script.
# The heredoc behaves like a file, so we read its contents
# with cat and redirect it to a real file
cat <<EOF > $1/info
This is an automated message generated at: `date`
Goodbye and thanks for all the fish
EOF

 

5. Foreach Loops

#!/Usr/bin/env tcsh

# A foreach loop allows running a command
# on multiple words (usually files)

foreach file (*.txt)
    # Note quoting the file variable to support
    # filenames with spaces
    echo "The End" >> "$file"
end

 

6. Conditions

#!/Usr/bin/env tcsh

# if checks for conditions. Remember to put then at
# the end of the same line, and use spaces aroung the operator

if ( $# > 0 ) then
    echo "Got $# args"
else
    echo "Usage: $0 <file name>"
    exit 1
endif

# Can also use file test
if ( -r $1 ) then
    echo "$1 is a readable file"
endif

 

7. Arithmetics

#!/Usr/bin/env tcsh

set num = 1

# Use @ to perform arithmetics in csh
@ num++

# Note no spaces between operator and operands
@ num+=5
@ num*=9

# Unless using an assignment. 
# Also, note $ inside parens to read variable's value
@ num = ($num + $#)

echo "Result: $num"