fish Scripting

586 2026-08-14 note ♑︎

fish scripting is cleaner and more readable than bash, with modern syntax and better error handling.

Script Structure

#!/usr/bin/env fish

# Comments start with #
echo "Hello, world!"

Variables

# Set variables
set name "World"

# Use variables
echo "Hello, $name"

# Variable scope
set -l local_var "local"    # Local to current block
set -g global_var "global"  # Global
set -U universal_var "universal"  # Universal (persistent)

Conditionals

if test -f "file.txt"
    echo "File exists"
else if test -d "file.txt"
    echo "File is a directory"
else
    echo "File not found"
end

Loops

# For loop
for file in *.txt
    echo "Processing: $file"
end

# While loop
set count 0
while test $count -lt 5
    echo $count
    set count (math $count + 1)
end

Functions

# Define function
function greet
    set name $argv[1]
    echo "Hello, $name!"
end

# Call function
greet "World"

# Function with default argument
function greet
    set name $argv[1] "World"
    echo "Hello, $name!"
end

Command Substitution

# Command substitution
set files (ls *.txt)
echo $files

# Piping
echo "hello" | string upper

String Manipulation

# String length
string length "hello"

# String upper/lower
string upper "hello"
string lower "HELLO"

# String split
string split "," "a,b,c"

# String replace
string replace "old" "new" "old string"

File Operations

# File test operators
test -f "file.txt"     # File exists
test -d "directory"    # Directory exists
test -r "file.txt"     # File is readable
test -w "file.txt"     # File is writable
test -x "file.txt"     # File is executable

# File operations
cat file.txt
head -n 10 file.txt
tail -n 10 file.txt

Error Handling

# Check command success
if command -v git
    echo "git is installed"
else
    echo "git is not installed"
end

# Set exit status
function my_function
    # Do something
    return 0  # Success
    return 1  # Failure
end

Arrays

# Create array
set colors red green blue

# Access array elements
echo $colors[1]  # red
echo $colors[-1] # blue

# Array length
set count (count $colors)

# Array slicing
echo $colors[1..2]  # red green

Path Operations

# Path manipulation
set path /home/user/file.txt
set dirname (dirname $path)
set basename (basename $path)
set extension (path extension $path)

Math Operations

# Basic math
math "1 + 2"
math "10 * 5"
math "10 / 2"

# Comparison
test 5 -gt 3
test 5 -eq 5
test 5 -lt 10

fish scripting provides a modern, clean alternative to bash with better readability and error handling.

For fish commands and built-in functions, see fish Commands. For configuration and setup, see fish Configuration. For the main fish overview, see fish.