Convert Figma logo to code with AI

anordal logoshellharden

The corrective bash syntax highlighter

4,606
129
4,606
5

Top Related Projects

ShellCheck, a static analysis tool for shell scripts

7,232

A shell parser, formatter, and interpreter with bash support; includes shfmt

Bash Automated Testing System

42,950

A tool for writing better scripts

7,122

Bash Automated Testing System

📖 A collection of pure POSIX sh alternatives to external processes.

Quick Overview

Shellharden is a tool designed to make shell scripts (bash) more robust and less error-prone. It automatically detects and fixes common shell scripting mistakes, helping developers write safer and more reliable scripts. The project aims to address the inherent fragility of shell scripts by enforcing best practices and safer syntax.

Pros

  • Automatically identifies and corrects common shell scripting errors
  • Improves script reliability and reduces potential for unexpected behavior
  • Educates users about shell scripting best practices through its corrections
  • Supports both interactive use and integration into development workflows

Cons

  • May produce overly cautious code in some cases, potentially affecting readability
  • Limited to bash scripting, not applicable to other shell languages
  • Requires users to trust the tool's judgment for automated fixes
  • May conflict with existing coding styles or preferences in some organizations

Getting Started

To use Shellharden, follow these steps:

  1. Install Shellharden:

    cargo install shellharden
    
  2. Run Shellharden on a shell script:

    shellharden script.sh
    
  3. To automatically apply fixes, use the --replace flag:

    shellharden --replace script.sh
    
  4. For more options and usage information, consult the help:

    shellharden --help
    

Competitor Comparisons

ShellCheck, a static analysis tool for shell scripts

Pros of ShellCheck

  • More comprehensive analysis with a wider range of checks and suggestions
  • Supports multiple shell dialects (bash, ksh, sh)
  • Integrates with various editors and CI systems

Cons of ShellCheck

  • Focuses on static analysis without automatic fixing
  • May produce false positives in some cases
  • Requires manual intervention to apply suggested fixes

Code Comparison

ShellCheck example:

# ShellCheck will flag this as an error
echo $VAR
# Suggestion: Double quote to prevent globbing and word splitting
echo "$VAR"

ShellHarden example:

# ShellHarden will automatically fix this
echo $VAR
# Fixed version:
echo "$VAR"

ShellCheck provides more detailed static analysis and supports multiple shell dialects, while ShellHarden focuses on automatically fixing common shell script issues. ShellCheck offers broader integration options but requires manual fixes, whereas ShellHarden applies fixes automatically but has a more limited scope. Both tools aim to improve shell script quality, with ShellCheck emphasizing comprehensive analysis and ShellHarden prioritizing automatic corrections for specific issues.

7,232

A shell parser, formatter, and interpreter with bash support; includes shfmt

Pros of sh

  • More comprehensive language support, including POSIX sh, Bash, and mksh
  • Offers parsing, formatting, and interpretation capabilities
  • Actively maintained with regular updates and improvements

Cons of sh

  • Primarily focused on parsing and formatting, less emphasis on hardening scripts
  • May require more setup and configuration for specific use cases
  • Larger codebase and potentially steeper learning curve

Code Comparison

sh:

f, err := syntax.NewParser().Parse(strings.NewReader(src), "")
if err != nil {
    log.Fatal(err)
}
syntax.NewPrinter().Print(os.Stdout, f)

shellharden:

let mut file = File::open(path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let hardened = harden(&content);
println!("{}", hardened);

Summary

sh is a more comprehensive tool for shell script parsing, formatting, and interpretation, supporting multiple shell dialects. It offers a wider range of features but may require more setup. shellharden, on the other hand, focuses specifically on hardening shell scripts, providing a simpler and more targeted approach to improving script safety and reliability. The choice between the two depends on the specific needs of the project and the desired level of functionality.

Bash Automated Testing System

Pros of bats-core

  • Focused on shell script testing, providing a robust framework for unit tests
  • Supports parallel test execution, improving performance for large test suites
  • Integrates well with CI/CD pipelines and other testing tools

Cons of bats-core

  • Limited to testing functionality, doesn't address shell script syntax or style issues
  • Requires writing separate test files, potentially increasing maintenance overhead
  • Steeper learning curve for those unfamiliar with testing frameworks

Code Comparison

bats-core example:

@test "addition using bc" {
  result="$(echo 2+2 | bc)"
  [ "$result" -eq 4 ]
}

shellharden example:

# Before
echo $foo

# After
echo "$foo"

Key Differences

shellharden focuses on improving shell script syntax and safety, automatically fixing common issues. It's a static analysis tool that helps prevent errors before runtime.

bats-core, on the other hand, is a testing framework for shell scripts. It allows developers to write and run tests to verify script functionality, but doesn't address syntax or style concerns.

While both tools aim to improve shell scripting, they serve different purposes. shellharden is best for enhancing script quality and preventing errors, while bats-core is ideal for ensuring script functionality through testing.

42,950

A tool for writing better scripts

Pros of zx

  • Allows writing shell scripts in JavaScript, providing better syntax and error handling
  • Offers built-in promise-based functions for common shell operations
  • Integrates well with Node.js ecosystem and npm packages

Cons of zx

  • Requires Node.js runtime, which may not be available in all environments
  • Learning curve for developers not familiar with JavaScript
  • May be overkill for simple shell scripts or quick one-liners

Code Comparison

shellharden:

#!/bin/sh
echo "Hello, $(whoami)!"
for file in *.txt; do
    cat "$file"
done

zx:

#!/usr/bin/env zx
echo`Hello, ${await $`whoami`}!`
for (const file of await glob('*.txt')) {
    await $`cat ${file}`
}

Summary

shellharden focuses on improving existing shell scripts by making them more robust and secure, while zx provides a JavaScript-based alternative to traditional shell scripting. shellharden is better suited for enhancing existing shell scripts and maintaining POSIX compatibility, whereas zx offers a more modern approach with improved readability and access to JavaScript features. The choice between the two depends on the specific project requirements, target environment, and developer preferences.

7,122

Bash Automated Testing System

Pros of Bats

  • Focused on testing shell scripts, providing a robust framework for unit testing
  • Supports test isolation and setup/teardown functions
  • Integrates well with continuous integration systems

Cons of Bats

  • Limited to testing functionality, doesn't address shell script hardening
  • Requires learning a specific testing syntax and conventions
  • May add complexity to simple shell script projects

Code Comparison

Shellharden example:

# Before
echo $var

# After
echo "$var"

Bats example:

@test "addition using bc" {
  result="$(echo 2+2 | bc)"
  [ "$result" -eq 4 ]
}

Key Differences

Shellharden focuses on improving shell script safety and robustness by automatically fixing common issues, while Bats is a testing framework for shell scripts. Shellharden modifies existing scripts to make them more secure, whereas Bats helps ensure script functionality through unit tests.

Shellharden is more suitable for developers looking to enhance script reliability without extensive manual changes. Bats is ideal for those implementing thorough testing practices in shell script development, especially in larger projects or continuous integration environments.

📖 A collection of pure POSIX sh alternatives to external processes.

Pros of pure-sh-bible

  • Comprehensive collection of shell scripting techniques and best practices
  • Focuses on POSIX-compliant shell scripting, enhancing portability
  • Includes practical examples and explanations for various shell operations

Cons of pure-sh-bible

  • Lacks automated tools for enforcing best practices
  • Does not provide real-time feedback or suggestions for script improvement
  • May require more manual effort to implement recommended practices

Code Comparison

shellharden example:

shellharden --replace script.sh

pure-sh-bible example:

# String manipulation
${variable#pattern}    # Remove from start (non-greedy)
${variable##pattern}   # Remove from start (greedy)
${variable%pattern}    # Remove from end (non-greedy)
${variable%%pattern}   # Remove from end (greedy)

Summary

shellharden is a tool that automatically corrects and hardens shell scripts, while pure-sh-bible is a comprehensive guide to shell scripting best practices. shellharden offers automated improvements, whereas pure-sh-bible provides in-depth knowledge and techniques for manual implementation. Both projects aim to enhance shell script quality, but they approach the goal differently: shellharden through automation and pure-sh-bible through education and reference.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build and test status

Shellharden

Shellharden is a syntax highlighter and a tool to semi-automate the rewriting of scripts to ShellCheck conformance, mainly focused on quoting.

The default mode of operation is like cat, but with syntax highlighting in foreground colors and suggestive changes in background colors:

real-world example

Above: Selected portions of xdg-desktop-menu as highlighted by Shellharden. The foreground colors are syntax highlighting, whereas the background colors (green and red) show characters that Shellharden would have added or removed if let loose with the --transform option. Below: An artificial example that shows more tricky cases and special features.

artificial example

Why

A variable in bash is like a hand grenade – take off its quotes, and it starts ticking. Hence, rule zero of bash pitfalls: Always use quotes.

Name

Shellharden can do what Shellcheck can't: Apply the suggested changes.

In other words, harden vulnerable shellscripts. The builtin assumption is that the script does not depend on the vulnerable behavior – the user is responsible for the code review.

Shellharden was previously known as "Naziquote". In the right jargon, that was the best name ever, but oh so misleading and unspeakable to outsiders.

I couldn't call it "bash cleaner" either, as that means "poo smearer" in Norwegian.

Prior art

  • Shellcheck is a wonderful tool to detect, and give general advice, about vulnerable bash code. The only thing missing is something to say yes with, and apply those advice (assuming proper review of course).

  • I asked this SO question, for a tool that could rewrite bash scripts with proper quoting. One answerer beat me to it. But if it was me, I would do a syntax highlighter in the same tool (as a way to see if the parser gets lost, and make the most out of the parser, because bash is like quantum mechanics – nobody really knows how it works).

Get it

Distro packages:

Packaging status

Official rust package:

cargo install shellharden

Build from source

cargo build --release

Install

mv target/release/shellharden ~/.local/bin/

Run tests

cargo test

(requires bash)

Test coverage

env RUSTFLAGS="-C instrument-coverage" LLVM_PROFILE_FILE='run-%m.profraw' cargo test
grcov . --binary-path ./target/debug/ -s . -t html -o ./coverage/
rm run-*.profraw
open coverage/src/index.html

Fuzz test

cargo install cargo-afl
cargo afl build --release
cargo afl fuzz -i moduletests/original -o /tmp/fuzz-shellharden target/release/shellharden ''

Usage advice

Don't apply --transform blindly; code review is still necessary: A script that relies on unquoted behavior (implicit word splitting and glob expansion from variables and command substitutions) to work as intended will do none of that after getting the --transform treatment!

In that unlucky case, ask yourself whether the script has any business in doing that. All too often, it's just a product of classical shellscripting, and would be better off rewritten, such as by using arrays. Even in the opposite case, say the business logic involves word splitting; that can still be done without invoking globbing. In short: There is always a better way than the forbidden syntax (if not more explicit), but some times, a human must step in to rewrite. See how, in the accompanying how to do things safely in bash.