DEV Community

David Li
David Li

Posted on

Script to checkout files from specified branch to current branch

Recently, I wrote a script to checkout files from branch because why not. At first I thought of using golang or C#, but bash scripting is the way to go.

In all honestly, this script was made with github copilot, its getting pretty powerful, but this script is also fairly simple.

#!/bin/sh

# this scripts reads files.txt and checks out the files from the repository from the inputted branch

# argument 1: branch name
# argument 2: file.txt

# check if the branch exists
if ! git show-ref --verify --quiet refs/heads/$1
then
    echo "Branch does not exist"
    exit 1
fi

# check if file exists
if [ ! -f $2 ]
then
    echo "File does not exist"
    exit 1
fi

# read the file and check out the files
while read line
do
  # convert line from windows path to unix path
  line=$(echo $line | sed 's/\\/\//g')
    echo "git checkout $1 -- $line"
    git checkout "$1" -- "$line"
done < $2
Enter fullscreen mode Exit fullscreen mode

Since I use windows + git bash we will need a convert windows file paths to unix, for now I use a simple approach of just parsing backslash.

For example a sample file.txt can be

package.json
app/src/file.goeshere.txt
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more