The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
├── .github
    ├── FUNDING.yml
    ├── ISSUE_TEMPLATE.md
    ├── PULL_REQUEST_TEMPLATE.md
    ├── stale.yml
    └── workflows
    │   └── shellcheck.yml
├── .gitignore
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── bak2dvd
    └── bak2dvd
├── bash-snippets.1
├── bash-snippets.1.html
├── bash-snippets.1.ronn
├── bash-snippets
    └── bash-snippets
├── changelog.md
├── cheat
    ├── cheat
    └── cheat.png
├── cloudup
    ├── cloudup
    └── cloudup.png
├── crypt
    ├── crypt
    └── crypt.png
├── cryptocurrency
    ├── cryptocurrency
    └── cryptocurrency.png
├── currency
    ├── currency
    └── currency.png
├── extras
    ├── Linux
    │   └── maps
    │   │   └── maps
    └── README.md
├── geo
    ├── geo
    └── geo.png
├── gist
    ├── README.md
    ├── gist
    └── gist.png
├── install.sh
├── lyrics
    ├── lyrics
    └── lyrics.png
├── meme
    ├── meme
    └── meme.png
├── movies
    ├── movies
    ├── movies.png
    └── tmdb
├── newton
    ├── newton
    └── newton.png
├── pwned
    └── pwned
├── qrify
    ├── qrify
    └── qrify.png
├── short
    ├── short
    └── short.png
├── siteciphers
    ├── siteciphers
    └── siteciphers.png
├── skeleton
├── skeleton.bats
├── stocks
    ├── stocks
    └── stocks.png
├── taste
    ├── taste
    └── taste.png
├── tests
    ├── bak2dvd.bats
    ├── cheat.bats
    ├── cloudup.bats
    ├── crypt.bats
    ├── cryptocurrency.bats
    ├── currency.bats
    ├── geo.bats
    ├── gist.bats
    ├── meme.bats
    ├── movies.bats
    ├── newton.bats
    ├── qrify.bats
    ├── short.bats
    ├── siteciphers.bats
    ├── stocks.bats
    ├── taste.bats
    ├── todo.bats
    ├── transfer.bats
    ├── weather.bats
    └── ytview.bats
├── todo
    ├── todo
    └── todo.png
├── transfer
    ├── transfer
    └── transfer.png
├── uninstall.sh
├── weather
    ├── moon.png
    ├── weather
    └── weather.png
└── ytview
    ├── ytview
    └── ytview.png


/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 | 
3 | github: [alexanderepstein]
4 | 


--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
 1 | **Issue Label:**
 2 | * [ ] Bug
 3 | * [ ] New feature
 4 | * [ ] Enhancement
 5 | * [ ] New component
 6 | 
 7 | **Description:**
 8 | 
 9 | 
10 | 
11 | ### If its a bug make sure to include this section.
12 | **OS and OS version:**
13 | * [ ] Mac
14 | * [ ] Linux 32 Bit
15 | * [ ] Linux 64 Bit
16 | * [ ] Windows 32 Bit
17 | * [ ] Windows 64 Bit
18 | 
19 | OS Version:
20 | 


--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
 1 | **Pull Request Label:**
 2 | * [ ] Bug
 3 | * [ ] New feature
 4 | * [ ] Enhancement
 5 | * [ ] New component
 6 | * [ ] Typo
 7 | 
 8 | **Pull Request Checklist:**
 9 | - [ ] Have you followed the [guidelines for contributing](https://github.com/alexanderepstein/Bash-Snippets/blob/master/CONTRIBUTING.md)?
10 | - [ ] Have you checked that there aren't other open [pull requests](https://github.com/alexanderepstein/Bash-Snippets/pulls) for the same fix or component?
11 | - [ ] Have you ran the tests locally with `bats tests`?
12 | 
13 | -----
14 | 


--------------------------------------------------------------------------------
/.github/stale.yml:
--------------------------------------------------------------------------------
 1 | # Number of days of inactivity before an issue becomes stale
 2 | daysUntilStale: 175
 3 | # Number of days of inactivity before a stale issue is closed
 4 | daysUntilClose: 5
 5 | # Issues with these labels will never be considered stale
 6 | exemptLabels:
 7 |   - New Component
 8 | # Label to use when marking an issue as stale
 9 | staleLabel: Stale
10 | # Comment to post when marking an issue as stale. Set to `false` to disable
11 | markComment: >
12 |   This issue has been automatically marked as stale because it has not had
13 |   recent activity. It will be closed if no further activity occurs. Thank you
14 |   for your contributions.
15 | # Comment to post when closing a stale issue. Set to `false` to disable
16 | closeComment: >
17 |   This issue has been automatically closed because it has been 
18 |   inactive for 180 days.
19 | 


--------------------------------------------------------------------------------
/.github/workflows/shellcheck.yml:
--------------------------------------------------------------------------------
 1 | on: push
 2 | jobs:
 3 |   shellcheck:
 4 |     name: Shellcheck
 5 |     runs-on: ubuntu-latest
 6 |     steps:
 7 |       - uses: actions/checkout@v2
 8 |       - name: Run ShellCheck
 9 |         uses: ludeeus/action-shellcheck@master
10 | 


--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # IDE
2 | .idea
3 | 
4 | # Meta files
5 | .DS_Store
6 | Thumbs.db


--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
 1 | language: bash
 2 | 
 3 | matrix:
 4 |   include:
 5 |     - os: linux
 6 |       dist: trusty
 7 |       sudo: required
 8 |     - os: osx
 9 |   allow_failures:
10 |     - os: linux
11 | 
12 | before_install:
13 |   - sudo ./install.sh all
14 |   - export TASTE_API_KEY='290044-Taste-QIQUQKOZ'
15 | 
16 | install:
17 |   - if [ $TRAVIS_OS_NAME = linux ]; then sudo add-apt-repository ppa:duggan/bats --yes; fi
18 |   - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get update; fi
19 |   - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get install -qq bats; else brew install bats; fi
20 |   - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get install -qq openssl; else brew install openssl; fi
21 | 
22 | script:
23 |   - bats tests
24 | 


--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
 1 | # Contributor Covenant Code of Conduct
 2 | 
 3 | ## Our Pledge
 4 | 
 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
 6 | 
 7 | ## Our Standards
 8 | 
 9 | Examples of behavior that contributes to creating a positive environment include:
10 | 
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 | 
17 | Examples of unacceptable behavior by participants include:
18 | 
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 | 
25 | ## Our Responsibilities
26 | 
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 | 
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 | 
31 | ## Scope
32 | 
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 | 
35 | ## Enforcement
36 | 
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at epsteina@wit.edu. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 | 
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 | 
41 | ## Attribution
42 | 
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 | 
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 | 


--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
 1 | # Contributing
 2 | 
 3 | ### First off, thank you for considering contributing to Bash-Snippets.
 4 | 
 5 | #### Where do I go from here?
 6 | 
 7 | If you've noticed a bug or have a question, search the <a href="https://github.com/alexanderepstein/Bash-Snippets/issues">issue tracker</a> to see if someone else in the community has already created a ticket. If not, go ahead and <a href="https://github.com/alexanderepstein/Bash-Snippets/issues/new">make one</a>!
 8 | 
 9 | #### Otherwise if implementing a fix, feature or new component go through these steps
10 | #### 1. Fork & Clone The Repository
11 | * Fork the repository
12 | * It is assumed you are on either a Unix or Linux system in which are there are no dependencies
13 | * To download the full source code after forking
14 | ```bash
15 | git clone https://github.com/yourusernamehere/Bash-Snippets
16 | ```   
17 | 
18 | 
19 | #### 2. Implement your fix, feature or new component
20 | 
21 | ###### Fix/Feature
22 | At this point, you're ready to make your changes!
23 | 
24 | ###### New Component
25 | * Decide on a short but sweet name for your tool
26 | * Create a folder in the Bash-Snippets root directory named after the tool
27 | * Copy over the Bash-Snippets tool [skeleton](https://github.com/alexanderepstein/Bash-Snippets/blob/master/skeleton) to the newly created folder
28 | * Rename the skeleton in the new directory to the name of the tool
29 | * Using newly copied over file as a basis (with the name of your tool) code your new component!
30 | 
31 | Feel free to ask for help; everyone is a beginner at first :smile_cat:
32 | Make sure to make your commit messages informative and concise.
33 | 
34 | 
35 | #### 3. Check The Script Runtime
36 | 
37 | If you changed the weather script for example try running it and see if it works as intended. Run ```bats tests``` when inside the Bash-Snippets directory to test the tools.
38 | If you added a new script/tool test it to see if it works.
39 | 
40 | #### 4. Create A Pull Request
41 | 
42 | First make sure to commit and push your changes to your forked repository.
43 | Check to see if there are any conflicts with the main repository and your fork.
44 | If there are none submit the request and give details as to what you changed or added.
45 | 
46 | #### 5. Bask In All The Glory Of Adding To A FOSS Application
47 | ![Had to do it to em](https://68.media.tumblr.com/2dfc3369827df9b981e111d7fd8fc732/tumblr_mvemcyarmn1rslphyo1_400.gif)
48 | 


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
 1 | MIT License
 2 | 
 3 | Copyright (c) 2017 Alex Epstein
 4 | 
 5 | Permission is hereby granted, free of charge, to any person obtaining a copy
 6 | of this software and associated documentation files (the "Software"), to deal
 7 | in the Software without restriction, including without limitation the rights
 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 | 
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 | 
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 | 


--------------------------------------------------------------------------------
/bash-snippets/bash-snippets:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Navan Chauhan and Alexander Epstein
  3 | declare -a tools=(bak2dvd cheat cloudup crypt cryptocurrency currency geo lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview)
  4 | declare -a validTools=()
  5 | currentVersion="1.23.0"
  6 | configuredClient=""
  7 | 
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredClient="wget"
 16 |   elif command -v http &>/dev/null; then
 17 |     configuredClient="httpie"
 18 |   elif command -v fetch &>/dev/null; then
 19 |     configuredClient="fetch"
 20 |   else
 21 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 22 |     return 1
 23 |   fi
 24 | }
 25 | 
 26 | httpGet()
 27 | {
 28 |   case "$configuredClient" in
 29 |     curl)  curl -A curl -s "$@" ;;
 30 |     wget)  wget -qO- "$@" ;;
 31 |     httpie) http -b GET "$@" ;;
 32 |     fetch) fetch -q "$@" ;;
 33 |   esac
 34 | }
 35 | 
 36 | grablatestversion()
 37 | {
 38 |   repositoryName="Bash-Snippets"
 39 |   githubUserName="alexanderepstein"
 40 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 41 | }
 42 | 
 43 | checkInternet()
 44 | {
 45 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 46 | }
 47 | 
 48 | header()
 49 | {
 50 |   title="Bash Snippets"
 51 |   installver="Installed Version: $currentVersion"
 52 |   latestver="Latest Version: $latestVersion"
 53 |   printf "\t\t\t\t     %s\n" "$title"
 54 |   printf "\t\t%s\t\t%s\n" "$latestver" "$installver"
 55 | }
 56 | 
 57 | 
 58 | toolMenu()
 59 | {
 60 |   while true; do
 61 |     clear
 62 |     header
 63 |     count=1
 64 |     for command in "${validTools[@]}"; do
 65 |       if [[ $count -gt 9 ]];then c=$count
 66 |       else c="0$count"; fi
 67 |       spaces=$((40 - $(echo "$command" | wc -c)))
 68 |       echo -n -e "\t\t\t$c."
 69 |       for (( i = 0 ; i < $spaces; i++)) ;do
 70 |         printf " "
 71 |       done
 72 |       echo "$command"
 73 |       count=$(( $count + 1 ))
 74 |     done
 75 |     echo -e -n "\t\tChoose a tool or just press enter to go back: "
 76 |     read choice
 77 |     if [[ $choice == "" ]];then clear; header; break; fi
 78 |     echo -e -n "\t\tEnter any arguments you want to use with the tool: "
 79 |     read args
 80 |     clear
 81 |     if [[ $choice =~ [0-9] ]]; then ${validTools[$(($choice-1))]} "$args"
 82 |     else $choice "$args"; fi
 83 |     exit 0
 84 |   done
 85 | }
 86 | 
 87 | menu()
 88 | {
 89 |   while true; do
 90 |     echo -e "\t\t\t01.\t\t\t\tTools"
 91 |     echo -e "\t\t\t02.\t\t\t\tInstallation Check"
 92 |     echo -e "\t\t\t03.\t\t\t\tView man page"
 93 |     echo -e "\t\t\t04.\t\t\t\tUpdate"
 94 |     echo -e "\t\t\t05.\t\t\t\tDonate"
 95 |     echo -e "\t\t\t06.\t\t\t\tQuit"
 96 |     echo -e -n "\n\t\t\tChoose an option: "
 97 |     read choice
 98 |     if [[ $choice -gt 6 || $choice -lt 1 ]];then
 99 |       echo "Error invalid option!"
100 |       sleep 2
101 |       clear
102 |       header
103 |       continue
104 |     fi
105 |     clear
106 |     header
107 |     if   [[ $choice -eq 1 ]];then toolMenu
108 |     elif [[ $choice -eq 2 ]];then installationcheck
109 |     elif [[ $choice -eq 3 ]];then man bash-snippets
110 |     elif [[ $choice -eq 4 ]];then
111 |       ${validTools[1]} -u
112 |       sleep 2
113 |       clear
114 |       header
115 |     elif [[ $choice -eq 5 ]];then
116 |       clear
117 |       echo -e "\t\tThanks for thinking of donating, that's pretty cool of you"
118 |       echo -e "\n\t\tCryptocurrency Donation Addresses"
119 |       echo -e "\t\t\tBTC: 38Q5VbH63MtouxHu8BuPNLzfY5B5RNVMDn"
120 |       echo -e "\t\t\tETH: 0xf7c60C06D298FF954917eA45206426f79d40Ac9D"
121 |       echo -e "\t\t\tLTC: LWZ3T19YUk66dgkczN7dRhiXDMqSYrXUV4\n"
122 |       echo -e "\t\tNormal Methods"
123 |       echo -e "\t\t\tVenmo: AlexanderEpstein"
124 |       echo -e "\t\t\tSquare Cash: AlexEpstein\n\n\n\n"
125 |       exit 0
126 |     elif [[ $choice -eq 6 ]]; then clear; exit 0
127 |     fi
128 |   done
129 | }
130 | 
131 | installationcheck()
132 | {
133 |   validTools=()
134 |   for tool in "${tools[@]}"; do
135 |     if [ -e "/usr/local/bin/$tool" ]; then
136 |       state="present";
137 |       start=51;
138 |       validTools+=($tool);
139 |     else state="absent"; start=52; fi
140 |       if $1; then
141 |         echo -n -e "\t\t$tool"
142 |         spaces=$(($start - $( echo "$tool" | wc -c)))
143 |         for (( i = 0 ; i < $spaces; i++)) ;do
144 |           printf " "
145 |         done
146 |         echo $state
147 |       fi
148 |   done
149 |   if $1; then
150 |     echo -n "Press enter to go back to the menu"
151 |     read
152 |     clear
153 |     header
154 |   fi
155 | }
156 | 
157 | if [[ $# -eq 0 ]]; then
158 |   clear
159 |   checkInternet
160 |   getConfiguredClient
161 |   grablatestversion
162 |   header
163 |   installationcheck false
164 |   echo
165 |   menu
166 | elif [[ $# -eq 1 ]]; then
167 |   if [[ $1 == "-u" || $1 == "update" ]]; then
168 |     installationcheck false
169 |     ${validTools[1]} -u
170 |   elif [[ $1 == "-h" || $1 == "help" ]]; then man bash-snippets
171 |   elif [[ $1 == "-v" ]]; then echo "Version $currentVersion"
172 |   fi
173 | 
174 | fi
175 | 


--------------------------------------------------------------------------------
/cheat/cheat:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | ## rest of these variables are search flags
  7 | search="0"
  8 | insensitive=""
  9 | recursive=""
 10 | boundry=""
 11 | 
 12 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 13 | getConfiguredClient()
 14 | {
 15 |   if  command -v curl &>/dev/null; then
 16 |     configuredClient="curl"
 17 |   elif command -v wget &>/dev/null; then
 18 |     configuredClient="wget"
 19 |   elif command -v http &>/dev/null; then
 20 |     configuredClient="httpie"
 21 |   elif command -v fetch &>/dev/null; then
 22 |     configuredClient="fetch"
 23 |   else
 24 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 25 |     return 1
 26 |   fi
 27 | }
 28 | 
 29 | ## Allows to call the users configured client without if statements everywhere
 30 | httpGet()
 31 | {
 32 |   case "$configuredClient" in
 33 |     curl)  curl -A curl -s "$@" ;;
 34 |     wget)  wget -qO- "$@" ;;
 35 |     httpie) http -b GET "$@" ;;
 36 |     fetch) fetch -q "$@" ;;
 37 |   esac
 38 | }
 39 | 
 40 | 
 41 | checkInternet()
 42 | {
 43 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 44 | }
 45 | 
 46 | update()
 47 | {
 48 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 49 |   # Update utility version 2.2.0
 50 |   # To test the tool enter in the defualt values that are in the examples for each variable
 51 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 52 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 53 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 54 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 55 | 
 56 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 57 |     echo "Error: update utility has not been configured correctly." >&2
 58 |     exit 1
 59 |   elif [[ $latestVersion == "" ]]; then
 60 |     echo "Error: no active internet connection" >&2
 61 |     exit 1
 62 |   else
 63 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 64 |       echo "Version $latestVersion available"
 65 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 66 |       read -r answer
 67 |       if [[ "$answer" == [Yy] ]]; then
 68 |         cd ~ || { echo 'Update Failed'; exit 1; }
 69 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 70 |         echo -n "Downloading latest version of: $repositoryName."
 71 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 72 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 73 |         rm -f .BSnippetsHiddenFile
 74 |         echo "Success!"
 75 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 76 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 77 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 78 |         ./$nameOfInstallFile "update" || exit 1
 79 |         cd ..
 80 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 81 |       else
 82 |         exit 1
 83 |       fi
 84 |     else
 85 |       echo "$repositoryName is already the latest version"
 86 |     fi
 87 |   fi
 88 | }
 89 | 
 90 | usage()
 91 | {
 92 | cat <<EOF
 93 | Cheat
 94 | Description: Cheatsheets for quick information about multiple programming languages along with terminal commands
 95 | Usage: cheat [flags] [command] or cheat [flags] [programming language] [subject]
 96 |   -s  Does a search for last argument rather than looking for exact match
 97 |   -i  Case insensitive search
 98 |   -b  Word boundaries in search
 99 |   -r  Recursive search
100 |   -u  Update Bash-Snippet Tools
101 |   -h  Show the help
102 |   -v  Get the tool version
103 | Special Pages:
104 |   hello      Describes building the hello world program written in the language
105 |   list       This lists all cheatsheets related to previous arg if none it lists all cheatsheets
106 |   learn      Shows a learn-x-in-minutes language cheat sheet perfect for getting started with the language
107 |   1line      A collection of one-liners in this language
108 |   weirdness  A collection of examples of weird things in this language
109 | Examples:
110 |   cheat rust hello
111 |   cheat -r -b -i go
112 |   cheat julia Functions
113 |   cheat -i go operators
114 | EOF
115 | }
116 | 
117 | getCheatSheet()
118 | {
119 |   if [[ $# == 1 ]]; then
120 |     if [[ $search == "1" ]]; then
121 |       link=cheat.sh/~$1
122 |     else
123 |       link=cheat.sh/$1
124 |     fi
125 |   else
126 |     link=cheat.sh/$1
127 |   fi
128 | 
129 |   if [[ $# == 2 ]]; then
130 |     if [[ $search == "1" ]]; then
131 |       link+=/~$2 ## add this to end of link where ~ indicates search
132 |     else
133 |       link+=/$2 ## add this to end of link
134 |     fi
135 |   fi
136 | 
137 |   if [[ $insensitive != "" || $recursive != "" || $boundry != "" ]]; then link+=/$boundry$insensitive$recursive; fi ## add this to the end of the link as flags
138 | 
139 |   httpGet $link
140 | }
141 | 
142 | 
143 | ### This function just wraps some of the special pages provided by cheat.sh
144 | checkSpecialPage()
145 | {
146 |   temp=$1
147 |   if [[ $1 == "list" ]]; then
148 |     temp=":list"
149 |   elif [[ $1 == "learn" ]]; then
150 |     temp=":list"
151 |   elif [[ $1 == "styles" ]]; then
152 |     temp=":styles"
153 |   fi
154 |   if [[ $2 == "1" ]]; then
155 |     arg1=$temp
156 |   else
157 |     arg2=$temp
158 |   fi
159 | }
160 | 
161 | getConfiguredClient || exit 1
162 | 
163 | 
164 | while getopts "ribuvhis" opt; do
165 |   case "$opt" in
166 |     \?) echo "Invalid option: -$OPTARG" >&2
167 |         exit 1
168 |         ;;
169 |     h)  usage
170 |         exit 0
171 |         ;;
172 |     v)  echo "Version $currentVersion"
173 |         exit 0
174 |         ;;
175 |     u)
176 |         checkInternet || exit 1
177 |         update
178 |         exit 0
179 |         ;;
180 |     i)  insensitive="i"
181 |         search="1"
182 |         ;;
183 |     b)  boundry="b"
184 |         search="1"
185 |         ;;
186 |     r)  recursive="r"
187 |         search="1"
188 |         ;;
189 |     s)  search="1"
190 |         ;;
191 |     :)  echo "Option -$OPTARG requires an argument." >&2
192 |         exit 1
193 |         ;;
194 |   esac
195 | done
196 | 
197 | ### This functions sets arg 1 and arg 2 to be unqique items after the options
198 | for arg; do
199 |   if [[ $arg != "-r" && $arg != "-s" && $arg != "-b" && $arg != "-i" ]]; then
200 |     if [ -z ${arg1+x} ]; then
201 |       arg1=$arg
202 |     fi
203 |     if [ ! -z ${arg1+x} ]; then
204 |       arg2=$arg
205 |     fi
206 |   fi
207 | done
208 | 
209 | ## check for special pages before moving on
210 | checkSpecialPage "$arg1" 1
211 | checkSpecialPage "$arg2" 2
212 | 
213 | if [[ $# == 0 ]]; then
214 |   usage
215 |   exit 0
216 | elif [[ $1 == "update" ]]; then
217 |   checkInternet || exit 1
218 |   update
219 |   exit 0
220 | elif [[ $1 == "help" || $1 == ":help" ]]; then ## shows the help and prevents the user from seeing cheat.sh/:help
221 |   usage
222 |   exit 0
223 | else
224 |   checkInternet || exit 1
225 |   if [[ $arg1 != $arg2 ]]; then ## if they equal each other that means there was no arg 2 supplied
226 |     getCheatSheet "$arg1" "$arg2"
227 |     exit 0
228 |   else
229 |     getCheatSheet "$arg1"
230 |     exit 0
231 |   fi
232 |   exit 0
233 | fi
234 | 


--------------------------------------------------------------------------------
/cheat/cheat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/cheat/cheat.png


--------------------------------------------------------------------------------
/cloudup/cloudup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/cloudup/cloudup.png


--------------------------------------------------------------------------------
/crypt/crypt:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | state=""
  6 | configuredClient=""
  7 | 
  8 | checkOpenSSL()
  9 | {
 10 |   if  ! command -v openssl &>/dev/null; then
 11 |     echo "Error: to use this tool openssl must be installed" >&2
 12 |     return 1
 13 |   else
 14 |     return 0
 15 |   fi
 16 | }
 17 | 
 18 | checkInternet()
 19 | {
 20 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 21 | }
 22 | 
 23 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 24 | getConfiguredClient()
 25 | {
 26 |   if  command -v curl &>/dev/null; then
 27 |     configuredClient="curl"
 28 |   elif command -v wget &>/dev/null; then
 29 |     configuredClient="wget"
 30 |   elif command -v http &>/dev/null; then
 31 |     configuredClient="httpie"
 32 |   elif command -v fetch &>/dev/null; then
 33 |     configuredClient="fetch"
 34 |   else
 35 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 36 |     return 1
 37 |   fi
 38 | }
 39 | 
 40 | ## Allows to call the users configured client without if statements everywhere
 41 | httpGet()
 42 | {
 43 |   case "$configuredClient" in
 44 |     curl)  curl -A curl -s "$@" ;;
 45 |     wget)  wget -qO- "$@" ;;
 46 |     httpie) http -b GET "$@" ;;
 47 |     fetch) fetch -q "$@" ;;
 48 |   esac
 49 | }
 50 | 
 51 | ## uses openssl aes 256 cbc encryption to encrypt file salting it with password designated by user
 52 | encrypt()
 53 | {
 54 |   echo "Encrypting $1..."
 55 |   openssl enc -aes-256-cbc -salt -a -in "$1" -out "$2" || { echo "File not found"; return 1; }
 56 |   echo "Successfully encrypted"
 57 | }
 58 | 
 59 | ## uses openssl aes 256 cbc decryption to decrypt file
 60 | decrypt()
 61 | {
 62 |   echo "Decrypting $1..."
 63 |   openssl enc -aes-256-cbc -d -a -in "$1" -out "$2" || { echo "File not found"; return 1; }
 64 |   echo "Successfully decrypted"
 65 | }
 66 | 
 67 | update()
 68 | {
 69 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 70 |   # Update utility version 2.2.0
 71 |   # To test the tool enter in the defualt values that are in the examples for each variable
 72 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 73 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 74 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 75 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 76 | 
 77 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 78 |     echo "Error: update utility has not been configured correctly." >&2
 79 |     exit 1
 80 |   elif [[ $latestVersion == "" ]]; then
 81 |     echo "Error: no active internet connection" >&2
 82 |     exit 1
 83 |   else
 84 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 85 |       echo "Version $latestVersion available"
 86 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 87 |       read -r answer
 88 |       if [[ "$answer" == [Yy] ]]; then
 89 |         cd ~ || { echo 'Update Failed'; exit 1; }
 90 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 91 |         echo -n "Downloading latest version of: $repositoryName."
 92 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 93 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 94 |         rm -f .BSnippetsHiddenFile
 95 |         echo "Success!"
 96 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 97 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 98 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 99 |         ./$nameOfInstallFile "update" || exit 1
100 |         cd ..
101 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
102 |       else
103 |         exit 1
104 |       fi
105 |     else
106 |       echo "$repositoryName is already the latest version"
107 |     fi
108 |   fi
109 | }
110 | 
111 | 
112 | usage()
113 | {
114 |   cat <<EOF
115 | Crypt
116 | Description: A wrapper around openssl that facilitates encrypting and decrypting files.
117 | Usage: crypt [flag] [inputFile] [outputFile]
118 |   -e  Encrypt the inputFile and store it in the outputFile
119 |   -d  Decrypt the inputFile and store it in the outputFile
120 |   -u  Update Bash-Snippet Tools
121 |   -h  Show the help
122 |   -v  Get the tool version
123 | Examples:
124 |   crypt -e mySecretFile.txt myEncryptedFile.jpg (change filetype so default program is incorrect)
125 |   crypt -d myEncryptedFile.jpg thisIsNowDecrypted.txt (change filetype back so now default program is correct)
126 | EOF
127 | }
128 | 
129 | checkOpenSSL || exit 1
130 | 
131 | while getopts "huve:d:" opt; do ## alows for using options in bash
132 |   case $opt in
133 |     e)  ## when trying to encrypt run this
134 |         if [[ $state != "decrypt" ]]; then
135 |           state="encrypt"
136 |         else
137 |           echo "Error: the -d and -e options are mutally exclusive" >&2
138 |           exit 1
139 |         fi
140 |         if [[ $# -ne 3 ]]; then
141 |           echo "Option -e needs and only accepts two arguments [file to encrypt] [output file]" >&2
142 |           exit 1
143 |         fi
144 |         ;;
145 |     \?) echo "Invalid option: -$OPTARG" >&2
146 |         exit 1
147 |         ;;
148 |     d)  ## when trying to decrypt run this
149 |         if [[ $state != "encrypt" ]]; then
150 |           state="decrypt"
151 |         else
152 |           echo "Error: the -e and -d options are mutally exclusive" >&2
153 |           exit 1
154 |         fi
155 |         if [[ $# -ne 3 ]]; then
156 |           echo "Option -d needs and only accepts two arguments [file to decrypt] [output file]" >&2
157 |           exit 1
158 |         fi
159 |         ;;
160 |     u)  getConfiguredClient || exit 1
161 |         checkInternet || exit 1
162 |         update
163 |         exit 0
164 |         ;;
165 |     h)  usage
166 |         exit 0
167 |         ;;
168 |     v)  echo "Version $currentVersion"
169 |         exit 0
170 |         ;;
171 |     :)  ## will run when no arguments are provided to to e or d options
172 |         echo "Option -$OPTARG requires an argument." >&2
173 |         exit 1
174 |         ;;
175 |   esac
176 | done
177 | 
178 | if [[ $# == 0 ]]; then
179 |   usage
180 |   exit 0
181 | elif [[ $1 == "update" ]]; then
182 |   getConfiguredClient || exit 1
183 |   checkInternet || exit 1
184 |   update || exit 1
185 |   exit 0
186 | elif [[ $1 == "help" ]]; then
187 |   usage
188 |   exit 0
189 | elif [[ $state == "encrypt" ]]; then
190 |   encrypt "$2" "$3" || exit 1
191 |   exit 0
192 | elif [[ $state == "decrypt" ]]; then
193 |   decrypt "$2" "$3" || exit 1
194 |   exit 0
195 | fi
196 | 


--------------------------------------------------------------------------------
/crypt/crypt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/crypt/crypt.png


--------------------------------------------------------------------------------
/cryptocurrency/cryptocurrency.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/cryptocurrency/cryptocurrency.png


--------------------------------------------------------------------------------
/currency/currency.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/currency/currency.png


--------------------------------------------------------------------------------
/extras/Linux/maps/maps:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | directionsFlag="0"
  7 | directionsMapFlag="0"
  8 | staticMapFlag="0"
  9 | source ~/.bash_profile 2> /dev/null ## allows grabbing enviornment variable
 10 | MAPQUEST_API_KEY=$MAPQUEST_API_KEY
 11 | if [ -d ~/temp ]; then rm -rf ~/temp; fi
 12 | 
 13 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 14 | getConfiguredClient()
 15 | {
 16 |   if  command -v curl &>/dev/null; then
 17 |     configuredClient="curl"
 18 |   elif command -v wget &>/dev/null; then
 19 |     configuredClient="wget"
 20 |   elif command -v http &>/dev/null; then
 21 |     configuredClient="httpie"
 22 |   elif command -v fetch &>/dev/null; then
 23 |     configuredClient="fetch"
 24 |   else
 25 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 26 |     return 1
 27 |   fi
 28 | }
 29 | 
 30 | ## Allows to call the users configured client without if statements everywhere
 31 | httpGet()
 32 | {
 33 |   case "$configuredClient" in
 34 |     curl)  curl -A curl -s "$@" ;;
 35 |     wget)  wget -qO- "$@" ;;
 36 |     httpie) http -b GET "$@" ;;
 37 |     fetch) fetch -q "$@" ;;
 38 |   esac
 39 | }
 40 | 
 41 | checkInternet()
 42 | {
 43 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 44 | }
 45 | 
 46 | update()
 47 | {
 48 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 49 |   # Update utility version 2.2.0
 50 |   # To test the tool enter in the defualt values that are in the examples for each variable
 51 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 52 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 53 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 54 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 55 | 
 56 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 57 |     echo "Error: update utility has not been configured correctly." >&2
 58 |     exit 1
 59 |   elif [[ $latestVersion == "" ]]; then
 60 |     echo "Error: no active internet connection" >&2
 61 |     exit 1
 62 |   else
 63 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 64 |       echo "Version $latestVersion available"
 65 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 66 |       read -r answer
 67 |       if [[ "$answer" == [Yy] ]]; then
 68 |         cd ~ || { echo 'Update Failed'; exit 1; }
 69 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 70 |         echo -n "Downloading latest version of: $repositoryName."
 71 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 72 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 73 |         rm -f .BSnippetsHiddenFile
 74 |         echo "Success!"
 75 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 76 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 77 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 78 |         ./$nameOfInstallFile "update" || exit 1
 79 |         cd ..
 80 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 81 |       else
 82 |         exit 1
 83 |       fi
 84 |     else
 85 |       echo "$repositoryName is already the latest version"
 86 |     fi
 87 |   fi
 88 | }
 89 | 
 90 | 
 91 | getDirections()
 92 | {
 93 |   response=$(httpGet "https://www.mapquestapi.com/directions/v2/route?key=$MAPQUEST_API_KEY&from=$1&to=$2&outFormat=json&ambiguities=ignore&routeType=fastest&doReverseGeocode=false&enhancedNarrative=false&avoidTimedConditions=false")
 94 |   firstDirection=$(echo "$response" | grep -Eo "origNarrative\":\"[a-z A-Z -./0-9]*" | grep -Eo "[^origNarrative\":][a-z A-Z -./0-9]*")
 95 |   tempDirections=($(echo "$response" | grep -Eo "\"narrative\":\"[a-z A-Z -./0-9]*"))
 96 |   distances=($(echo "$response" | grep -Eo "distance\":[0-9]*[.][0-9]*" | grep -Eo "[^distance\":][0-9]*[.][0-9]*"))
 97 |   totalDist=${distances[0]}
 98 |   count="0"
 99 |   count="-1"
100 |   temp=${tempDirections[0]}
101 |   for direct in "${tempDirections[@]}"; do
102 |     if [[ $(echo "$direct" | grep -Eo "narrative") == "narrative" ]]; then
103 |       count=$(echo $count + 1 | bc)
104 |       directions[$count]=$temp
105 |       temp=$(echo "$direct" | grep -Eo "[^\"narrative:\"][a-z A-Z 0-9./]*" | sed s/'","iconUrl"'//g)
106 |     else
107 |       temp="$temp $direct"
108 |     fi
109 |   done
110 |   #for distance in $tempDistances
111 |   directions[0]=$firstDirection
112 | }
113 | 
114 | getDirectionsMap()
115 | {
116 |   echo "Generating route map from $unformattedFromLocation to $unformattedToLocation"
117 |   mkdir ~/temp || return 1
118 |   httpGet "https://www.mapquestapi.com/staticmap/v5/map?start=$1&end=$2&size=600,400@2x&key=$MAPQUEST_API_KEY" >> ~/temp/routeImage.png || return 1
119 |   if [[ $(uname -s) == "Linux" ]]; then
120 |     display ~/temp/routeImage.png > /dev/null || return 1
121 |   elif [[ $(uname -s) == "Darwin" ]]; then
122 |     open ~/temp/routeImage.png > /dev/null
123 |   fi
124 |   rm -rf ~/temp > /dev/null
125 | }
126 | 
127 | printDirections()
128 | {
129 |   echo
130 |   echo "From $unformattedFromLocation to $unformattedToLocation ($totalDist mi)"
131 |   echo "==================================================="
132 |   count=0
133 |   for direct in "${directions[@]}"; do
134 |     if [ $count -ne 0 ]; then echo -n "$(echo $count | bc)). "; fi
135 |     if [[ $direct != "" ]]; then # sometimes original Narrative is blank
136 |       direct="$direct (${distances[$(echo $count + 1 | bc)]} mi)"
137 |       if [ $count -ne 0 ]; then echo "$direct"; fi
138 |       count=$(echo $count + 1 | bc)
139 |     fi
140 |   done
141 |   echo "Welcome to $unformattedToLocation"
142 |   echo "==================================================="
143 |   echo
144 | }
145 | 
146 | getLocations()
147 | {
148 |   echo -n "Enter your starting location: "
149 |   read fromLocation
150 |   echo -n "Enter your destination: "
151 |   read toLocation
152 |   unformattedFromLocation=$fromLocation
153 |   unformattedToLocation=$toLocation
154 |   fromLocation=$(echo "$fromLocation" | sed s/','/"+"/g | sed  s/' '/"+"/g )
155 |   toLocation=$(echo "$toLocation" | sed s/','/"+"/g | sed  s/' '/"+"/g )
156 | }
157 | 
158 | checkImagemagick()
159 | {
160 |   if [[ $(uname -s) == "Linux" ]]; then
161 |     if ! command -v display &>/dev/null; then
162 |       echo "Error: you need to install imagemagick to use map features." &>2
163 |       return 1
164 |     else
165 |       return 0
166 |     fi
167 |   else
168 |     return 0
169 |   fi
170 | }
171 | 
172 | getMapLocation()
173 | {
174 |   echo -n "Enter the city or address you want to generate a map for: "
175 |   read mapLocation
176 |   echo "Generating static map for $mapLocation"
177 |   mapLocation=$(echo "$mapLocation" | sed  s/','/"+"/g | sed  s/' '/"+"/g )
178 | }
179 | 
180 | getStaticMap()
181 | {
182 |   mkdir ~/temp || return 1
183 |   httpGet "https://www.mapquestapi.com/staticmap/v5/map?key=$MAPQUEST_API_KEY&center=$1&zoom=15&type=hyb&size=600,400@2x" >> ~/temp/mapImage.png || return 1
184 |   if [[ $(uname -s) == "Linux" ]]; then
185 |     display ~/temp/mapImage.png > /dev/null || return 1
186 |   elif [[ $(uname -s) == "Darwin" ]]; then
187 |     open ~/temp/mapImage.png > /dev/null || return 1
188 |   fi
189 |   rm -rf ~/temp > /dev/null || return 1
190 | }
191 | 
192 | usage()
193 | {
194 |   cat <<EOF
195 | Maps
196 | Description: Get directions between locations, generate static maps of locations, and generate route maps for directions.
197 | Usage: maps [flags]
198 |     -u  Update Bash-Snippet Tools
199 |     -d  Get directions from a location to a destination
200 |     -r  Generate route map (must be used with the -d flag)
201 |     -m  Generate static map
202 |           * By itself will ask for a location to generate a map
203 |           * In conjunction with the -d flag will generate maps for the start location and the destination
204 |     -h  Show the help
205 |     -v  Get the tool version
206 | Examples:
207 |     maps -d
208 |     maps -d -r -m
209 |     maps -m
210 |     maps -d -m
211 | EOF
212 | }
213 | 
214 | getConfiguredClient || exit 1
215 | 
216 | ## getDirections Denver Boulder || exit 1
217 | ## printDirections Denver Boulder || exit 1
218 | ## getDirectionsMap Denver Boulder || exit 1
219 | ## getStaticMap Paramus || exit 1
220 | 
221 | while getopts "drmuvh" opt; do
222 |   case "$opt" in
223 |     \?) echo "Invalid option: -$OPTARG" >&2
224 |         exit 1
225 |         ;;
226 |     h)  usage
227 |         exit 0
228 |         ;;
229 |     d)  directionsFlag="1" ;;
230 |     m)  staticMapFlag="1" ;;
231 |     r)  directionsMapFlag="1" ;;
232 |     v)  echo "Version $currentVersion"
233 |         exit 0
234 |         ;;
235 |     u)  checkInternet || exit 1
236 |         update
237 |         exit 0
238 |         ;;
239 |     :)  echo "Option -$OPTARG requires an argument." >&2
240 |         exit 1
241 |         ;;
242 |   esac
243 | done
244 | 
245 | if [[ $directionsMapFlag == "1" && $directionsFlag == "0" ]]; then { echo "Error the -r flag only works in conjunction with the -d flag."; exit 1; }; fi
246 | 
247 | if [[ $# == 0 ]]; then
248 |   usage
249 |   exit 0
250 | elif [[ $# == "1" ]]; then
251 |   if [[ $1 == "update" ]]; then
252 |     checkInternet || exit 1
253 |     update
254 |     exit 0
255 |   elif [[ $1 == "help" ]]; then
256 |     usage
257 |     exit 0
258 |   fi
259 | fi
260 | checkInternet || exit 1
261 | if [[ $directionsFlag == "0" && $staticMapFlag == "1" ]]; then
262 |   checkImagemagick || exit 1
263 |   getMapLocation || exit 1
264 |   getStaticMap "$mapLocation" || exit 1
265 | elif [[ $directionsFlag == "1" ]]; then
266 |   getLocations || exit 1
267 |   getDirections "$fromLocation" "$toLocation" || exit 1
268 |   printDirections "$fromLocation" "$toLocation" || exit 1
269 |   checkImagemagick || exit 1
270 |   if [[ $directionsMapFlag == "1" ]]; then getDirectionsMap "$fromLocation" "$toLocation" || exit 1; fi
271 |   if [[ $staticMapFlag = "1" ]]; then
272 |     echo "Generating static map for $unformattedFromLocation" && getStaticMap "$fromLocation" || exit 1
273 |     echo "Generating static map for $unformattedToLocation" && getStaticMap "$toLocation"  || exit 1
274 |   fi
275 | fi
276 | 


--------------------------------------------------------------------------------
/extras/README.md:
--------------------------------------------------------------------------------
 1 | <div align="center">
 2 | 
 3 | # Bash-Snippets Extras
 4 | 
 5 | </div>
 6 | 
 7 | ## Why are these here?
 8 | 
 9 | If there is a tool in this folder that means it is not part of the main installer pipeline
10 | 
11 | It was removed or never made it to the pipeline only for two possible reasons:
12 | * It is platform dependent meaning it doesn't work the same on all \*nix machines
13 | * It had many dependencies that aren't native to all forms of \*nix
14 | 
15 | ## Can I install these & is it safe
16 | Yes you can install these, only tools that are considered to be fully functional will make it here. Just make sure you only install extras for the correct platform and if they require dependencies make sure to install them (although the tool itself should remind you of this)
17 | 
18 | ## Install
19 | To install the tool just ```cd``` into the folder of the tool and run ```cp toolNameGoesHere /usr/local/bin || echo "Run the install as sudo" ```
20 | 
21 | ## Uninstall
22 | To uninstall the tool just run ```rm -f /usr/local/bin/toolNameGoesHere || echo "Run the uninstall as sudo" ```. Notice that the recursive flag is not set so even if you accidentally go to remove ```/usr/local/bin``` the flags will not let you delete the directory.
23 | 
24 | ## Platform Specific Tools
25 | 
26 | ### Linux
27 | 
28 | #### Maps
29 | * Provides driving directions from a certain location to another
30 | * Generates a route map of the trip and displays it
31 | * Generates maps of the from and to locations and displays them
32 | * The map functions require imagemagick to be installed
33 | 
34 | ### OSX
35 | None for now
36 | 
37 | ## Dependent tools
38 | None for now
39 | 
40 | ## License
41 | MIT License
42 | 
43 | Copyright (c) 2017 Alex Epstein
44 | 
45 | Permission is hereby granted, free of charge, to any person obtaining a copy
46 | of this software and associated documentation files (the "Software"), to deal
47 | in the Software without restriction, including without limitation the rights
48 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
49 | copies of the Software, and to permit persons to whom the Software is
50 | furnished to do so, subject to the following conditions:
51 | 
52 | The above copyright notice and this permission notice shall be included in all
53 | copies or substantial portions of the Software.
54 | 
55 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
56 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
57 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
58 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
59 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
60 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
61 | SOFTWARE.
62 | 


--------------------------------------------------------------------------------
/geo/geo:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | 
  3 | # Bash utility for getting specific network info
  4 | # Author: Jake Meyer
  5 | # Github: https://github.com/jakewmeyer
  6 | 
  7 | currentVersion="1.23.0"
  8 | configuredClient=""
  9 | 
 10 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 11 | getConfiguredClient()
 12 | {
 13 |   if  command -v curl &>/dev/null; then
 14 |     configuredClient="curl"
 15 |   elif command -v wget &>/dev/null; then
 16 |     configuredClient="wget"
 17 |   elif command -v http &>/dev/null; then
 18 |     configuredClient="httpie"
 19 |   elif command -v fetch &>/dev/null; then
 20 |     configuredClient="fetch"
 21 |   else
 22 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 23 |     return 1
 24 |   fi
 25 | }
 26 | 
 27 | ## Allows to call the users configured client without if statements everywhere
 28 | httpGet()
 29 | {
 30 |   case "$configuredClient" in
 31 |     curl)  curl -A curl -s "$@" ;;
 32 |     wget)  wget -qO- "$@" ;;
 33 |     httpie) http -b GET "$@" ;;
 34 |     fetch) fetch -q "$@" ;;
 35 |   esac
 36 | }
 37 | 
 38 | # Parse arguments passed + help formatting
 39 | usage() {
 40 |   cat <<EOF
 41 | Geo
 42 | Description: Provides quick access for wan, lan, router, dns, mac, and ip geolocation data
 43 | Usage: geo [flag]
 44 |   -w  Returns WAN IP
 45 |   -l  Returns LAN IP(s)
 46 |   -r  Returns Router IP
 47 |   -d  Returns DNS Nameserver
 48 |   -m  Returns MAC address for interface. Ex. eth0
 49 |   -g  Returns Current IP Geodata
 50 | Examples:
 51 |   geo -g
 52 |   geo -wlrdgm eth0
 53 | Custom Geo Output => [all] [query] [city] [region] [country] [zip] [isp]
 54 | Example: geo -a 8.8.8.8 -o city,zip,isp
 55 |   -o [options]  Returns Specific Geodata
 56 |   -a [address]  For specific IP in -s
 57 |   -v            Returns Version
 58 |   -h            Returns Help Screen
 59 |   -u            Updates Bash-Snippets
 60 | EOF
 61 |     exit
 62 | }
 63 | 
 64 | # Displays version number
 65 | version() {
 66 |   echo "Version $currentVersion"
 67 | }
 68 | 
 69 | # Fetches WAN IP address
 70 | wan_search() {
 71 |   httpGet https://api.ipify.org
 72 | }
 73 | 
 74 | # Fetches current LAN IP address
 75 | lan_search() {
 76 |   if [ "$(uname)" = "Darwin" ]; then
 77 |     ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
 78 |   elif [ "$(uname -s)" = "Linux" ]; then
 79 |     ip addr show | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
 80 |   else
 81 |     echo "OS not supported"
 82 |     exit 1
 83 |   fi
 84 | }
 85 | 
 86 | # Fetches Router ip address
 87 | router_search() {
 88 |   if [ "$(uname)" = "Darwin" ]; then
 89 |     netstat -rn | grep default | head -1 | awk '{print$2}'
 90 |   elif [ "$(uname -s)" = "Linux" ]; then
 91 |     ip route | grep ^default'\s'via | head -1 | awk '{print$3}'
 92 |   else
 93 |     echo "OS not supported"
 94 |     exit 1
 95 |   fi
 96 | }
 97 | 
 98 | # Fetches DNS nameserver
 99 | dns_search() {
100 |   if [ "$(uname)" = "Darwin" ]; then
101 |     grep -i nameserver /etc/resolv.conf |head -n1|cut -d ' ' -f2
102 |   elif [ "$(uname -s)" = "Linux" ]; then
103 |     cat /etc/resolv.conf | grep -i ^nameserver | cut -d ' ' -f2
104 |   else
105 |     echo "OS not supported"
106 |     exit 1
107 |   fi
108 | }
109 | 
110 | # Fetches MAC address of
111 | mac_search() {
112 |   if [ "$(uname)" = "Darwin" ]; then
113 |     ifconfig "$MAC" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
114 |   elif [ "$(uname -s)" = "Linux" ]; then
115 |     ip addr show "$MAC" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | grep -v ff:
116 |   else
117 |     echo "OS not supported"
118 |     exit 1
119 |   fi
120 | }
121 | 
122 | # Fetches current geodata based on ip
123 | geodata_search() {
124 |   httpGet "http://ip-api.com/line/?fields=query,city,region,country,zip,isp"
125 | }
126 | 
127 | # Fetches specific geodata based on args
128 | specific_geo() {
129 |   if [ "$OPTIONS" = "all" ]; then
130 |     httpGet "http://ip-api.com/line/${ADDRESS}?fields=query,city,region,country,zip,isp"
131 |   else
132 |     httpGet "http://ip-api.com/line/${ADDRESS}?fields=${OPTIONS}"
133 |   fi
134 | }
135 | 
136 | update()
137 | {
138 |   # Author: Alexander Epstein https://github.com/alexanderepstein
139 |   # Update utility version 2.2.0
140 |   # To test the tool enter in the defualt values that are in the examples for each variable
141 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
142 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
143 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
144 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
145 | 
146 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
147 |     echo "Error: update utility has not been configured correctly." >&2
148 |     exit 1
149 |   elif [[ $latestVersion == "" ]]; then
150 |     echo "Error: no active internet connection" >&2
151 |     exit 1
152 |   else
153 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
154 |       echo "Version $latestVersion available"
155 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
156 |       read -r answer
157 |       if [[ "$answer" == [Yy] ]]; then
158 |         cd ~ || { echo 'Update Failed'; exit 1; }
159 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
160 |         echo -n "Downloading latest version of: $repositoryName."
161 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
162 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
163 |         rm -f .BSnippetsHiddenFile
164 |         echo "Success!"
165 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
166 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
167 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
168 |         ./$nameOfInstallFile "update" || exit 1
169 |         cd ..
170 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
171 |       else
172 |         exit 1
173 |       fi
174 |     else
175 |       echo "$repositoryName is already the latest version"
176 |     fi
177 |   fi
178 | }
179 | 
180 | checkInternet() {
181 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
182 | }
183 | 
184 | # Option parsing "controller"
185 | optspec="uwlrdm:go:a:vh*:"
186 | while getopts "$optspec" optchar; do
187 |   case "${optchar}" in
188 |     w) getConfiguredClient && checkInternet && wan_search || exit 1 ;;
189 |     l) lan_search ;;
190 |     r) router_search ;;
191 |     d) dns_search ;;
192 |     m) MAC=$OPTARG mac_search ;;
193 |     g) getConfiguredClient && checkInternet && geodata_search || exit 1 ;;
194 |     a) ADDRESS=$OPTARG ;;
195 |     o) getConfiguredClient && checkInternet && OPTIONS=$OPTARG specific_geo || exit 1 ;;
196 |     v) version ;;
197 |     h) usage ;;
198 |     u) getConfiguredClient && checkInternet && update || exit 1 ;;
199 |     *) usage ;;
200 |   esac
201 | done
202 | 
203 | # Makes geo command default to help screen for usability
204 | if [ $# -eq 0 ]; then
205 |   usage
206 |   exit 0
207 | elif [[ $1 == "update" ]]; then
208 |   getConfiguredClient && checkInternet && update || exit 1
209 | elif [[ $1 == "help" ]]; then
210 |   usage
211 |   exit 0
212 | fi
213 | 


--------------------------------------------------------------------------------
/geo/geo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/geo/geo.png


--------------------------------------------------------------------------------
/gist/gist.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/gist/gist.png


--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | currentVersion="1.23.0"
  4 | declare -a tools=(bak2dvd bash-snippets cheat cloudup crypt cryptocurrency currency geo gist lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview)
  5 | declare -a extraLinuxTools=(maps)
  6 | declare -a extraDarwinTools
  7 | usedGithubInstallMethod="0"
  8 | prefix="/usr/local"
  9 | 
 10 | askInstall()
 11 | {
 12 |   read -p "Do you wish to install $1 [Y/n]: " answer
 13 |   answer=${answer:-Y}
 14 | 
 15 |   if [[ "$answer" == [Yy] ]]; then
 16 |     cd "$1" || return 1
 17 |     echo -n "Installing $1: "
 18 |     chmod a+x "$1"
 19 |     cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; }
 20 |     echo "Success"
 21 |     cd .. || return 1
 22 |   fi
 23 | }
 24 | 
 25 | updateTool()
 26 | {
 27 |   if [[ -f  /usr/local/bin/$1 ]]; then
 28 |     usedGithubInstallMethod="1"
 29 |     cd "$1" || return 1
 30 |     echo -n "Installing $1: "
 31 |     chmod a+x "$1"
 32 |     cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; }
 33 |     echo "Success"
 34 |     cd .. || return 1
 35 |   fi
 36 | }
 37 | 
 38 | extraUpdateTool()
 39 | {
 40 |   if [[ -f  /usr/local/bin/$1 ]]; then
 41 |     usedGithubInstallMethod="1"
 42 |     cd extras || return 1
 43 |     cd "$2" || return 1
 44 |     cd "$1" || return 1
 45 |     echo -n "Installing $1: "
 46 |     chmod a+x "$1"
 47 |     cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; }
 48 |     echo "Success"
 49 |     cd .. || return 1
 50 |     cd .. || return 1
 51 |     cd .. || return 1
 52 |   fi
 53 | }
 54 | 
 55 | singleInstall()
 56 | {
 57 |   cd "$1" || exit 1
 58 |   echo -n "Installing $1: "
 59 |   chmod a+x "$1"
 60 |   cp "$1" $prefix/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; }
 61 |   echo "Success"
 62 |   cd .. || exit 1
 63 | }
 64 | 
 65 | copyManpage()
 66 | {
 67 |   manPath="$prefix/share/man/man1"
 68 |   if [ -f "$prefix/man/man1/bash-snippets.1" ]; then rm -f "$prefix/man/man1/bash-snippets.1"; fi
 69 |   cp bash-snippets.1 $manPath 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; }
 70 | }
 71 | 
 72 | response=$( echo "$@" | grep -Eo "\-\-prefix")
 73 | 
 74 | if [[ $response == "--prefix" ]]; then
 75 |   prefix=$(echo -n "$@" | sed -e 's/--prefix=\(.*\) .*/\1/' | cut -d " " -f 1)
 76 |   mkdir -p "$prefix"/bin "$prefix"/share/man/man1
 77 |   if [[ $2 == "all" ]];then
 78 |     for tool in "${tools[@]}"; do
 79 |       singleInstall "$tool" || exit 1
 80 |     done
 81 |   else
 82 |     for tool in "${@:2}"; do
 83 |       singleInstall "$tool" || exit 1
 84 |     done
 85 |   fi
 86 |   copyManpage || exit 1
 87 | elif [[ $# == 0 ]]; then
 88 |   for tool in "${tools[@]}"; do
 89 |     askInstall "$tool" || exit 1
 90 |   done
 91 |   copyManpage || exit 1
 92 | elif [[ $1 == "update" ]]; then
 93 |   echo "Updating scripts..."
 94 |   for tool in "${tools[@]}"; do
 95 |     updateTool "$tool" || exit 1
 96 |   done
 97 |   if [[ $(uname -s) == "Linux" ]]; then
 98 |     for tool in "${extraLinuxTools[@]}"; do
 99 |       extraUpdateTool "$tool" Linux || exit 1
100 |     done
101 |   fi
102 |   if [[ $(uname) == "Darwin" ]];then
103 |     for tool in "${extraDarwinTools[@]}"; do
104 |       extraUpdateTool "$tool" Darwin || exit 1
105 |     done
106 |   fi
107 |   if [[ $usedGithubInstallMethod == "1" ]]; then
108 |     copyManpage || exit 1
109 |   else
110 |     echo "It appears you have installed bash-snippets through a package manager, you must update it with the respective package manager."
111 |     exit 1
112 |   fi
113 | elif [[ $1 == "all" ]]; then
114 |   for tool in "${tools[@]}"; do
115 |     singleInstall "$tool" || exit 1
116 |   done
117 |   copyManpage || exit 1
118 | else
119 |   singleInstall "$1" || exit 1
120 |   copyManpage || exit 1
121 | fi
122 | 
123 | echo -n "( •_•)"
124 | sleep .75
125 | echo -n -e "\r( •_•)>⌐■-■"
126 | sleep .75
127 | echo -n -e "\r               "
128 | echo  -e "\r(⌐■_■)"
129 | sleep .5
130 | echo "Bash Snippets version $currentVersion"
131 | echo  "https://github.com/alexanderepstein/Bash-Snippets"
132 | 


--------------------------------------------------------------------------------
/lyrics/lyrics:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | currentVersion="1.23.0"
  4 | configuredClient=""
  5 | artist="false"
  6 | song="false"
  7 | filePath=""
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredClient="wget"
 16 |   elif command -v http &>/dev/null; then
 17 |     configuredClient="httpie"
 18 |   elif command -v fetch &>/dev/null; then
 19 |     configuredClient="fetch"
 20 |   else
 21 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 22 |     return 1
 23 |   fi
 24 | }
 25 | 
 26 | getConfiguredPython()
 27 | {
 28 |   if command -v python3 &>/dev/null; then
 29 |     configuredPython="python3"
 30 |   elif  command -v python2 &>/dev/null; then
 31 |     configuredPython="python2"
 32 |   elif command -v python &>/dev/null; then
 33 |     configuredPython="python"
 34 |   else
 35 |     echo "Error: This tool requires python to be installed."
 36 |     return 1
 37 |   fi
 38 | }
 39 | 
 40 | if [[ $(uname) != "Darwin" ]]; then
 41 |   python()
 42 |   {
 43 |     case "$configuredPython" in
 44 |       python3) python3 "$@" ;;
 45 |       python2) python2 "$@" ;;
 46 |       python)  python "$@" ;;
 47 |     esac
 48 |   }
 49 | fi
 50 | 
 51 | ## Grabs an element from a a json string and then echoes it to stdout
 52 | ## $1 = the JSON string
 53 | ## $n+1 = the elements to be indexed
 54 | AccessJsonElement() {
 55 |   json="$1"
 56 |   shift
 57 |   accessor=""
 58 |   for element in "$@"; do
 59 |       accessor="${accessor}['$element']"
 60 |   done
 61 |   echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" 2> /dev/null
 62 |   return "$?"
 63 | }
 64 | 
 65 | 
 66 | 
 67 | ## Allows to call the users configured client without if statements everywhere
 68 | httpGet()
 69 | {
 70 |   case "$configuredClient" in
 71 |     curl)  curl -A curl -s "$@" ;;
 72 |     wget)  wget -qO- "$@" ;;
 73 |     httpie) http -b GET "$@" ;;
 74 |     fetch) fetch -q "$@" ;;
 75 |   esac
 76 | }
 77 | 
 78 | update()
 79 | {
 80 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 81 |   # Update utility version 1.2.0
 82 |   # To test the tool enter in the defualt values that are in the examples for each variable
 83 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 84 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 85 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 86 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 87 | 
 88 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 89 |     echo "Error: update utility has not been configured correctly." >&2
 90 |     exit 1
 91 |   elif [[ $latestVersion == "" ]]; then
 92 |     echo "Error: no active internet connection" >&2
 93 |     exit 1
 94 |   else
 95 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 96 |       echo "Version $latestVersion available"
 97 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 98 |       read -r answer
 99 |       if [[ "$answer" == [Yy] ]]; then
100 |         cd ~ || { echo 'Update Failed'; exit 1; }
101 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
102 |         git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; }
103 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
104 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
105 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
106 |         ./$nameOfInstallFile "update" || exit 1
107 |         cd ..
108 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
109 |       else
110 |         exit 1
111 |       fi
112 |     else
113 |       echo "$repositoryName is already the latest version"
114 |     fi
115 |   fi
116 | }
117 | 
118 | checkInternet()
119 | {
120 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
121 | }
122 | 
123 | getLyrics()
124 | {
125 |   encodedArtist=$(echo "$1" | sed s/" "/%20/g | sed s/"&"/%26/g | sed s/,/%2C/g | sed s/-/%2D/g)
126 |   encodedSong=$(echo "$2" | sed s/" "/%20/g | sed s/"&"/%26/g | sed s/,/%2C/g | sed s/-/%2D/g)
127 |   response=$(httpGet "https://api.lyrics.ovh/v1/$encodedArtist/$encodedSong")
128 |   lyrics="$(AccessJsonElement "$response" "lyrics" 2> /dev/null)"
129 |   if [[ $lyrics == "" ]];then { echo "Error: no lyrics found!"; return 1; }; fi
130 | }
131 | 
132 | printLyrics()
133 | {
134 |   if [[ $filePath == "" ]];then echo -e "$lyrics"
135 |   else
136 |     if [ -f "$filePath" ];then
137 |       echo -n "File already exists, do you want to overwrite it [Y/n]: "
138 |       read -r answer
139 |       if [[ "$answer" == [Yy] ]]; then
140 |         echo -e "$lyrics" > "$filePath";
141 |       fi
142 |     else
143 |         echo -e "$lyrics" > "$filePath";
144 |     fi
145 |    fi
146 | }
147 | 
148 | usage()
149 | {
150 |   cat <<EOF
151 | Lyrics
152 | Description: Fetch lyrics for a certain song.
153 | Usage: lyrics [flags] or tool [-a] [arg] [-s] [arg]
154 |   -a  Artist of the song to fetch lyrics for
155 |   -s  Song of the artist to fetch lyrics for
156 |   -f  Export the lyrics to file rather than outputting to stdout
157 |   -u  Update Bash-Snippet Tools
158 |   -h  Show the help
159 |   -v  Get the tool version
160 | Examples:
161 |    lyrics -a logic -s run it
162 |    lyrics -a logic -s run it -f ~/runItLyrics.txt
163 | EOF
164 | }
165 | 
166 | 
167 | while getopts "f:a:s:uvh" opt; do
168 |   case "$opt" in
169 |     \?) echo "Invalid option: -$OPTARG" >&2
170 |         exit 1
171 |         ;;
172 |     h)  usage
173 |         exit 0
174 |         ;;
175 |     v)  echo "Version $currentVersion"
176 |         exit 0
177 |         ;;
178 |     u)
179 |         getConfiguredClient || exit 1
180 |         checkInternet || exit 1
181 |         update
182 |         exit 0
183 |         ;;
184 |     f)
185 |        filePath="$OPTARG"
186 |         ;;
187 |     a)
188 |         artist="true"
189 |         if [[ "$(echo "$@" | grep -Eo "\-s")" == "-s" ]];then song="true";fi # wont go through both options if arg spaced and not quoted this solves that issue (dont need this but once had bug on system where it was necessary)
190 |         if [[ "$(echo "$@" | grep -Eo "\-f")" == "-f" ]];then filePath=$(echo "$@" | grep -Eo "\-f [ a-z A-Z / 0-9 . \ ]*[ -]?" | sed s/-f//g | sed s/-//g | sed s/^" "//g);fi
191 |       ;;
192 |     s)
193 |         song="true"
194 |         if [[ "$(echo "$@" | grep -Eo "\-a")" == "-a" ]];then artist="true";fi # wont go through both options if arg spaced and not quoted this solves that issue (dont need this but once had bug on system where it was necessary)
195 |         if [[ "$(echo "$@" | grep -Eo "\-f")" == "-f" ]];then filePath=$(echo "$@" | grep -Eo "\-f [ a-z A-Z / 0-9 . \ ]*[ -]?" | sed s/-f//g | sed s/-//g | sed s/^" "//g);fi
196 |       ;;
197 |     :)  echo "Option -$OPTARG requires an argument." >&2
198 |         exit 1
199 |         ;;
200 |   esac
201 | done
202 | 
203 | # special set of first arguments that have a specific behavior across tools
204 | if [[ $# == "0" ]]; then
205 |   usage ## if calling the tool with no flags and args chances are you want to return usage
206 |   exit 0
207 | elif [[ $# == "1" ]]; then
208 |   if [[ $1 == "update" ]]; then
209 |     getConfiguredClient || exit 1
210 |     checkInternet || exit 1
211 |     update || exit 1
212 |     exit 0
213 |   elif [[ $1 == "help" ]]; then
214 |     usage
215 |     exit 0
216 |   fi
217 | fi
218 | 
219 | if ($artist && ! $song)  || ($song && ! $artist);then
220 |   echo "Error: the -a and the -s flag must be used to fetch lyrics."
221 |   exit 1
222 | elif $artist && $song;then
223 |   song=$(echo "$@" | grep -Eo "\-s [ a-z A-Z 0-9 . \ ]*[ -]?" | sed s/-s//g | sed s/-//g | sed s/^" "//g)
224 |   if [[ $song == "" ]];then { echo "Error: song could not be parsed from input."; exit 1; };fi
225 |   artist=$(echo "$@" | grep -Eo "\-a [ a-z A-Z 0-9 . \ ]*[ -]?" | sed s/-a//g | sed s/-//g | sed s/^" "//g)
226 |   if [[ $artist == "" ]];then { echo "Error: artist could not be parsed from input."; exit 1; };fi
227 |   getConfiguredClient || exit 1
228 |   if [[ $(uname) != "Darwin" ]]; then getConfiguredPython || exit 1;fi
229 |   checkInternet || exit 1
230 |   getLyrics "$artist" "$song" || exit 1
231 |   printLyrics
232 | else
233 |   { clear; echo "You shouldnt be here but maaaaaaybeee you slipped passed me, learn to use the tool!"; sleep 5; clear;}
234 |   usage
235 |   exit 1
236 | fi
237 | 


--------------------------------------------------------------------------------
/lyrics/lyrics.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/lyrics/lyrics.png


--------------------------------------------------------------------------------
/meme/meme:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Navan Chauhan https://github.com/navanchauhan
  3 | currentVersion="1.23.0"
  4 | configuredClient=""
  5 | fileName=""
  6 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
  7 | getConfiguredClient()
  8 | {
  9 |   if  command -v curl &>/dev/null; then
 10 |     configuredClient="curl"
 11 |   elif command -v wget &>/dev/null; then
 12 |     configuredClient="wget"
 13 |   elif command -v http &>/dev/null; then
 14 |     configuredClient="httpie"
 15 |   elif command -v fetch &>/dev/null; then
 16 |     configuredClient="fetch"
 17 |   else
 18 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 19 |     return 1
 20 |   fi
 21 | }
 22 | 
 23 | ## Allows to call the users configured client without if statements everywhere
 24 | httpGet()
 25 | {
 26 |   case "$configuredClient" in
 27 |     curl)  curl -A curl -Ls "$@" ;;
 28 |     wget)  wget -qO- "$@" ;;
 29 |     httpie) http -b GET "$@" ;;
 30 |     fetch) fetch -q "$@" ;;
 31 |   esac
 32 | }
 33 | 
 34 | update()
 35 | {
 36 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 37 |   # Update utility version 1.2.0
 38 |   # To test the tool enter in the defualt values that are in the examples for each variable
 39 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 40 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 41 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 42 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 43 | 
 44 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 45 |     echo "Error: update utility has not been configured correctly." >&2
 46 |     exit 1
 47 |   elif [[ $latestVersion == "" ]]; then
 48 |     echo "Error: no active internet connection" >&2
 49 |     exit 1
 50 |   else
 51 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 52 |       echo "Version $latestVersion available"
 53 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 54 |       read -r answer
 55 |       if [[ "$answer" == [Yy] ]]; then
 56 |         cd ~ || { echo 'Update Failed'; exit 1; }
 57 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 58 |         git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; }
 59 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 60 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 61 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 62 |         ./$nameOfInstallFile "update" || exit 1
 63 |         cd ..
 64 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 65 |       else
 66 |         exit 1
 67 |       fi
 68 |     else
 69 |       echo "$repositoryName is already the latest version"
 70 |     fi
 71 |   fi
 72 | }
 73 | 
 74 | checkInternet()
 75 | {
 76 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 77 | }
 78 | 
 79 | main(){
 80 |     echo -n "Enter the name for the meme's background (Ex. buzz, doge, blb ): "
 81 |     read bg
 82 |     echo -n "Enter the text for the first line: "
 83 |     read raw_first
 84 |     almost_first=$(echo "$raw_first" | awk '{print tolower($0)}')
 85 |     first=$(echo "$almost_first" | sed -e 's/ /_/g')
 86 |     echo -n "Enter the text for the second line: "
 87 |     read raw_second
 88 |     almost_second=$(echo "$raw_second" | awk '{print tolower($0)}')
 89 |     second=$(echo "$almost_second" | sed -e 's/ /_/g')
 90 |     if [ -z "$first" ]
 91 |     then
 92 |     first=$(echo "_")
 93 |     else
 94 |       echo ""
 95 |     fi
 96 |     if [ -z "$second" ]
 97 |     then
 98 |     second=$(echo "_")
 99 |     else
100 |       echo ""
101 |     fi
102 |     httpGet "https://memegen.link/$bg/$first/$second.jpg"  >> "$fileName".png || return 1
103 |     return 0
104 | }
105 | 
106 | usage()
107 | {
108 |   cat <<EOF
109 | Meme
110 | Description: A lightning fast meme generator
111 | Usage: tool [flags] or tool [flags] [arguments]
112 |   -u  Update Bash-Snippet Tools
113 |   -h  Show the help
114 |   -f  Choose the output filename
115 |   -v  Get the tool version
116 | Examples:
117 |    meme -h
118 |    meme -f dogeMeme
119 | EOF
120 | }
121 | 
122 | 
123 | 
124 | while getopts "uvhf:" opt; do
125 |   case "$opt" in
126 |     \?) echo "Invalid option: -$OPTARG" >&2
127 |         exit 1
128 |         ;;
129 |     h)  usage
130 |         exit 0
131 |         ;;
132 |     v)  echo "Version $currentVersion"
133 |         exit 0
134 |         ;;
135 |     u)  getConfiguredClient || exit 1
136 |         checkInternet || exit 1
137 |         update
138 |         exit 0
139 |         ;;
140 |     f)
141 |         fileName=$OPTARG
142 |         getConfiguredClient || exit 1
143 |         checkInternet || exit 1
144 |         main || exit 1
145 |         exit 0
146 |     ;;
147 |     :)  echo "Option -$OPTARG requires an argument." >&2
148 |         exit 1
149 |         ;;
150 |   esac
151 | done
152 | 
153 | 
154 | 
155 | 
156 | # special set of first arguments that have a specific behavior across tools
157 | if [[ $# == "0" ]]; then
158 |   getConfiguredClient || exit 1
159 |   checkInternet || exit 1
160 |   if [[ $fileName == "" ]]; then
161 |     fileName="meme"
162 |   fi
163 |   main || exit 1
164 |   exit 0
165 | elif [[ $# == "1" ]]; then
166 |   if [[ $1 == "update" ]]; then
167 |     getConfiguredClient || exit 1
168 |     checkInternet || exit 1
169 |     update || exit 1
170 |     exit 0
171 |   elif [[ $1 == "help" ]]; then
172 |     usage
173 |     exit 0
174 |   fi
175 | fi
176 | 


--------------------------------------------------------------------------------
/meme/meme.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/meme/meme.png


--------------------------------------------------------------------------------
/movies/movies:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | configuredPython=""
  7 | detail=false
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredClient="wget"
 16 |   elif command -v http &>/dev/null; then
 17 |     configuredClient="httpie"
 18 |   elif command -v fetch &>/dev/null; then
 19 |     configuredClient="fetch"
 20 |   else
 21 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 22 |     return 1
 23 |   fi
 24 | }
 25 | 
 26 | ## Allows to call the users configured client without if statements everywhere
 27 | httpGet()
 28 | {
 29 |   case "$configuredClient" in
 30 |     curl)  curl -A curl -s "$@" ;;
 31 |     wget)  wget -qO- "$@" ;;
 32 |     httpie) http -b GET "$@" ;;
 33 |     fetch) fetch -q "$@" ;;
 34 |   esac
 35 | }
 36 | 
 37 | getConfiguredPython()
 38 | {
 39 |   if command -v python3 &>/dev/null; then
 40 |     configuredPython="python3"
 41 |   elif  command -v python2 &>/dev/null; then
 42 |     configuredPython="python2"
 43 |   elif command -v python &>/dev/null; then
 44 |     configuredPython="python"
 45 |   else
 46 |     echo "Error: This tool requires python to be installed."
 47 |     return 1
 48 |   fi
 49 | }
 50 | 
 51 | if [[ $(uname) != "Darwin" ]]; then
 52 |   python()
 53 |   {
 54 |     case "$configuredPython" in
 55 |       python3) python3 "$@" ;;
 56 |       python2) python2 "$@" ;;
 57 |       python)  python "$@" ;;
 58 |     esac
 59 |   }
 60 | fi
 61 | 
 62 | ## Grabs an element from a a json string and then echoes it to stdout
 63 | ## $1 = the JSON string
 64 | ## $n+1 = the elements to be indexed
 65 | AccessJsonElement() {
 66 |   json="$1"
 67 |   shift
 68 |   accessor=""
 69 |   for element in "$@"; do
 70 |       accessor="${accessor}['$element']"
 71 |   done
 72 |   echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" 2> /dev/null
 73 |   return "$?"
 74 | }
 75 | 
 76 | checkInternet()
 77 | {
 78 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 79 | }
 80 | 
 81 | ## This function grabs information about a movie and using python parses the
 82 | ## JSON response to extrapolate the information for storage
 83 | getMovieInfo()
 84 | {
 85 |   apiKey=e3aeac39 # try not to abuse this it is a key that came from the ruby-scripts repo I link to.
 86 |   movie=$( (echo "$@" | tr " " + ) | sed 's/-d+//g' ) ## format the inputs to use for the api. Added sed command to filter -d flag.
 87 |   export PYTHONIOENCODING=utf8 #necessary for python in some cases
 88 |   movieInfo=$(httpGet "http://www.omdbapi.com/?t=$movie&apikey=$apiKey") > /dev/null # query the server and get the JSON response
 89 | 
 90 |   ## check to see if the movie was found
 91 |   checkResponse=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Response'])" 2> /dev/null)
 92 |   if [[ $checkResponse == "False" ]]; then
 93 |     echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Error'])" 2> /dev/null
 94 |     return 1
 95 |   fi
 96 | 
 97 |   # The rest of the code is just extrapolating the data with python from the JSON response
 98 |   title="$(AccessJsonElement "$movieInfo" "Title")"
 99 |   year="$(AccessJsonElement "$movieInfo" "Year")"
100 |   runtime="$(AccessJsonElement "$movieInfo" "Runtime")"
101 |   imdbScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][0]['Value'])" 2> /dev/null)
102 |   tomatoScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][1]['Value'])" 2> /dev/null)
103 |   rated="$(AccessJsonElement "$movieInfo" "Rated")"
104 |   genre="$(AccessJsonElement "$movieInfo" "Genre")"
105 |   director="$(AccessJsonElement "$movieInfo" "Director")"
106 |   actors="$(AccessJsonElement "$movieInfo" "Actors")"
107 |   plot="$(AccessJsonElement "$movieInfo" "Plot")"
108 |   
109 |   if $detail; then
110 |     awards="$(AccessJsonElement "$movieInfo" "Awards")"
111 |     boxOffice="$(AccessJsonElement "$movieInfo" "BoxOffice")"
112 |     metacriticScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][2]['Value'])" 2> /dev/null)
113 |     production="$(AccessJsonElement "$movieInfo" "Production")"
114 |   fi
115 | }
116 | 
117 | # Print key: value info
118 | printKV() {
119 |   key=$1
120 |   val=$2
121 |   ROW="|%11s: %-40s|\n"
122 |   WIDTH=53
123 | 
124 |   # If value too long (greater then 43 char), split it into several line
125 |   if [[ ${#val} -le $((WIDTH - 10)) ]]; then
126 |     printf "$ROW" "$key" "$val"
127 |   else
128 |     printf "$ROW" "$key"
129 |     printf "%s\n" "$val" | fmt -w 50 \
130 |     | while IFS= read -r line; do printf "|  %-50s |\n" "$line"; done
131 |   fi
132 | }
133 | 
134 | # Prints the movie information out in a human readable format
135 | printMovieInfo()
136 | {
137 |   echo
138 |   echo '+=====================================================+'
139 |   printKV "Title" "$title"
140 |   printKV "Year" "$year"
141 |   printKV "Runtime" "$runtime"
142 |   if [[ $imdbScore != "" ]]; then printKV "IMDB" "$imdbScore"; fi
143 |   if [[ $tomatoScore != "" ]]; then printKV "Tomato" "$tomatoScore"; fi
144 |   if $detail; then
145 |     if [[ $metacriticScore != "" ]]; then printKV "Metascore" "$metacriticScore"; fi
146 |   fi
147 |   if [[ $rated != "N/A" && $rated != "" ]]; then printKV "Rated" "$rated"; fi
148 |   printKV "Genre" "$genre"
149 |   printKV "Director" "$director"
150 |   printKV "Actors" "$actors"
151 |   if [[ $plot != "N/A" && $plot != "" ]]; then printKV "Plot" "$plot"; fi
152 |   if $detail; then
153 |     if [[ $boxOffice != "" ]]; then printKV "BoxOffice" "$boxOffice"; fi
154 |     if [[ $production != "" ]]; then printKV "Production" "$production"; fi
155 |     if [[ $awards != "" ]]; then printKV "Awards" "$awards"; fi
156 |   fi
157 |   echo '+=====================================================+'
158 |   echo
159 | }
160 | 
161 | update()
162 | {
163 |   # Author: Alexander Epstein https://github.com/alexanderepstein
164 |   # Update utility version 2.2.0
165 |   # To test the tool enter in the defualt values that are in the examples for each variable
166 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
167 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
168 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
169 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
170 | 
171 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
172 |     echo "Error: update utility has not been configured correctly." >&2
173 |     exit 1
174 |   elif [[ $latestVersion == "" ]]; then
175 |     echo "Error: no active internet connection" >&2
176 |     exit 1
177 |   else
178 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
179 |       echo "Version $latestVersion available"
180 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
181 |       read -r answer
182 |       if [[ "$answer" == [Yy] ]]; then
183 |         cd ~ || { echo 'Update Failed'; exit 1; }
184 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
185 |         echo -n "Downloading latest version of: $repositoryName."
186 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
187 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
188 |         rm -f .BSnippetsHiddenFile
189 |         echo "Success!"
190 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
191 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
192 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
193 |         ./$nameOfInstallFile "update" || exit 1
194 |         cd ..
195 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
196 |       else
197 |         exit 1
198 |       fi
199 |     else
200 |       echo "$repositoryName is already the latest version"
201 |     fi
202 |   fi
203 | }
204 | 
205 | usage()
206 | {
207 |   cat <<EOF
208 | Movies
209 | Description: Provides relevant information about a certain movie.
210 | Usage: movies [flag] or movies [movieToSearch]
211 |   -u  Update Bash-Snippet Tools
212 |   -h  Show the help
213 |   -v  Get the tool version
214 |   -d  Show detailed information
215 | Examples:
216 |   movies Argo
217 |   movies Inception
218 | EOF
219 | }
220 | 
221 | if [[ $(uname) != "Darwin" ]]; then getConfiguredPython || exit 1; fi
222 | getConfiguredClient || exit 1
223 | 
224 | 
225 | while getopts 'ud:hv' flag; do
226 |   case "${flag}" in
227 |     u) checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here
228 |       update
229 |        exit 0 ;;
230 |     d) detail=true ;;
231 |     h) usage
232 |        exit 0 ;;
233 |     v) echo "Version $currentVersion"
234 |        exit 0 ;;
235 |     :) echo "Option -$OPTARG requires an argument." >&2
236 |        exit 1 ;;
237 |     *) exit 1 ;;
238 |   esac
239 | done
240 | 
241 | if [[ $# == 0 ]]; then
242 |   usage
243 | elif [[ $1 == "update" ]]; then
244 |   checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here
245 |   update
246 | elif [[ $1 == "help" ]]; then
247 |   usage
248 | else
249 |   checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here
250 |   getMovieInfo "$@" || exit 1 ## exit if we return 1 (chances are movie was not found)
251 |   printMovieInfo ## print out the data
252 | fi
253 | 


--------------------------------------------------------------------------------
/movies/movies.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/movies/movies.png


--------------------------------------------------------------------------------
/movies/tmdb:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | # Author: Navan Chauhan https://github.com/navanchauhan
  4 | 
  5 | currentVersion="1.23.0"
  6 | configuredClient=""
  7 | configuredPython=""
  8 | APIKEY="b2f8880475c888056b6207067fbaa197"
  9 | 
 10 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 11 | getConfiguredClient()
 12 | {
 13 |   if  command -v curl &>/dev/null; then
 14 |     configuredClient="curl"
 15 |   elif command -v wget &>/dev/null; then
 16 |     configuredClient="wget"
 17 |   elif command -v http &>/dev/null; then
 18 |     configuredClient="httpie"
 19 |   elif command -v fetch &>/dev/null; then
 20 |     configuredClient="fetch"
 21 |   else
 22 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 23 |     return 1
 24 |   fi
 25 | }
 26 | 
 27 | ## Allows to call the users configured client without if statements everywhere
 28 | httpGet()
 29 | {
 30 |   case "$configuredClient" in
 31 |     curl)  curl -A curl -s "$@" ;;
 32 |     wget)  wget -qO- "$@" ;;
 33 |     httpie) http -b GET "$@" ;;
 34 |     fetch) fetch -q "$@" ;;
 35 |   esac
 36 | }
 37 | 
 38 | getConfiguredPython()
 39 | {
 40 |   if  command -v python2 &>/dev/null ; then
 41 |     configuredPython="python2"
 42 |   elif command -v python &>/dev/null ; then
 43 |     configuredPython="python"
 44 |   else
 45 |     echo "Error: This tool requires python 2 to be installed."
 46 |     return 1
 47 |   fi
 48 | }
 49 | 
 50 | if [[ $(uname) != "Darwin" ]]; then
 51 |   python()
 52 |   {
 53 |     case "$configuredPython" in
 54 |       python2) python2 "$@";;
 55 |       python) python "$@";;
 56 |     esac
 57 |   }
 58 | fi
 59 | 
 60 | checkInternet()
 61 | {
 62 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 63 | }
 64 | 
 65 | 
 66 | update()
 67 | {
 68 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 69 |   # Update utility version 1.2.0
 70 |   # To test the tool enter in the defualt values that are in the examples for each variable
 71 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 72 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 73 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 74 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 75 | 
 76 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 77 |     echo "Error: update utility has not been configured correctly." >&2
 78 |     exit 1
 79 |   elif [[ $latestVersion == "" ]];then
 80 |     echo "Error: no active internet connection" >&2
 81 |     exit 1
 82 |   else
 83 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 84 |       echo "Version $latestVersion available"
 85 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 86 |       read -r answer
 87 |       if [[ "$answer" == [Yy] ]]; then
 88 |         cd  ~ || { echo 'Update Failed' ; exit 1; }
 89 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 90 |         git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version" ; exit 1; }
 91 |         cd $repositoryName ||  { echo 'Update Failed' ; exit 1; }
 92 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 93 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 94 |         ./$nameOfInstallFile "update" || exit 1
 95 |         cd ..
 96 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 97 |       else
 98 |         exit 1
 99 |       fi
100 |     else
101 |       echo "$repositoryName is already the latest version"
102 |     fi
103 |   fi
104 | }
105 | 
106 | printMovieInfo()
107 | {
108 |   echo
109 |   echo "=========================================="
110 |   echo "| Title: $name"
111 |   echo "| Language: $language"
112 |   echo "| Genre: $genres"
113 |   echo "| Runtime: $runtime mins"
114 |   echo "| User Rating: $voteAverage/10.0 with $voteCount votes"
115 |   echo "| Plot: $plot"
116 |   echo "=========================================="
117 |   echo
118 | }
119 | 
120 | usage()
121 | {
122 |   cat <<EOF
123 | Movies
124 | Description: Provides relevant information about a certain movie.
125 | Usage: movies [flag] or movies [movieToSearch]
126 |   -u  Update Bash-Snippet Tools
127 |   -h  Show the help
128 |   -v  Get the tool version
129 | Examples:
130 |   movies Argo
131 |   movies Inception
132 | EOF
133 | }
134 | 
135 | getMovieInfo()
136 | {
137 |   title=$1
138 |   encodedTitle=$( echo "$title" | sed 's/ /%20/g' );
139 |   movieSearchInfo=$( httpGet "https://api.themoviedb.org/3/search/movie?query=$encodedTitle&language=en-US&api_key=$APIKEY")
140 |   movieID=$(echo "$movieSearchInfo" | python -c "import sys, json; print json.load(sys.stdin)['results'][0]['id']" 2> /dev/null)
141 |   if [[ $movieID == "" ]];then { echo "Error: could not find a movie matching the title $title"; return 1; }; fi
142 |   movieInfo=$(httpGet "https://api.themoviedb.org/3/movie/$movieID?api_key=$APIKEY")
143 |   name=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['original_title']" 2> /dev/null )
144 |   plot=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['overview']" 2> /dev/null )
145 |   language=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['original_language']" 2> /dev/null )
146 |   runtime=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['runtime']" 2> /dev/null )
147 |   voteCount=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['vote_count']" 2> /dev/null )
148 |   genreOne=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][0]['name']" 2> /dev/null )
149 |   genreTwo=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][1]['name']" 2> /dev/null )
150 |   genreThree=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][2]['name']" 2> /dev/null )
151 |   genres=$(echo "$genreOne $genreTwo $genreThree" | tr " " ",")
152 |   voteAverage=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['vote_average']" 2> /dev/null )
153 | }
154 | 
155 | getConfiguredClient || exit 1
156 | if [[ "$(uname)" == "Linux" ]];then getConfiguredPython || exit 1; fi
157 | checkInternet || exit 1
158 | 
159 | 
160 | while getopts 'uhv' flag; do
161 |   case "${flag}" in
162 |     u) update
163 |        exit 0 ;;
164 |     h) usage
165 |        exit 0 ;;
166 |     v) echo "Version $currentVersion"
167 |        exit 0 ;;
168 |     :) echo "Option -$OPTARG requires an argument." >&2
169 |        exit 1 ;;
170 |     *) exit 1 ;;
171 |   esac
172 | done
173 | 
174 | if [[ $# == 0 ]]; then
175 |   usage
176 | elif [[ $1 == "update" ]]; then
177 |   update
178 | elif [[ $1 == "help" ]]; then
179 |   usage
180 | else
181 |   getMovieInfo "$@" || exit 1 ## exit if we return 1 (chances are movie was not found)
182 |   printMovieInfo ## print out the data
183 | fi
184 | 


--------------------------------------------------------------------------------
/newton/newton:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | flagCount="0"
  7 | declare -a simpleOperations=(simplify factor derive integrate zeroes roots tangent area cos sin tan arccos arcsin arctan abs log)
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredClient="wget"
 16 |   elif command -v http &>/dev/null; then
 17 |     configuredClient="httpie"
 18 |   elif command -v fetch &>/dev/null; then
 19 |     configuredClient="fetch"
 20 |   else
 21 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 22 |     return 1
 23 |   fi
 24 | }
 25 | 
 26 | ## Allows to call the users configured client without if statements everywhere
 27 | httpGet()
 28 | {
 29 |   case "$configuredClient" in
 30 |     curl)  curl -A curl -s "$@" ;;
 31 |     wget)  wget -qO- "$@" ;;
 32 |     httpie) http -b GET "$@" ;;
 33 |     fetch) fetch -q "$@" ;;
 34 |   esac
 35 | }
 36 | 
 37 | 
 38 | checkInternet()
 39 | {
 40 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 41 | }
 42 | 
 43 | 
 44 | update()
 45 | {
 46 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 47 |   # Update utility version 2.2.0
 48 |   # To test the tool enter in the defualt values that are in the examples for each variable
 49 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 50 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 51 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 52 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 53 | 
 54 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 55 |     echo "Error: update utility has not been configured correctly." >&2
 56 |     exit 1
 57 |   elif [[ $latestVersion == "" ]]; then
 58 |     echo "Error: no active internet connection" >&2
 59 |     exit 1
 60 |   else
 61 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 62 |       echo "Version $latestVersion available"
 63 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 64 |       read -r answer
 65 |       if [[ "$answer" == [Yy] ]]; then
 66 |         cd ~ || { echo 'Update Failed'; exit 1; }
 67 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 68 |         echo -n "Downloading latest version of: $repositoryName."
 69 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 70 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 71 |         rm -f .BSnippetsHiddenFile
 72 |         echo "Success!"
 73 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 74 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 75 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 76 |         ./$nameOfInstallFile "update" || exit 1
 77 |         cd ..
 78 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 79 |       else
 80 |         exit 1
 81 |       fi
 82 |     else
 83 |       echo "$repositoryName is already the latest version"
 84 |     fi
 85 |   fi
 86 | }
 87 | 
 88 | validateExpression()
 89 | {
 90 |   local parsedExpression # only used here
 91 |   originalEquation=$(echo "$1" | sed "s/\[/\(/g" | sed "s/\]/\)/g") # accont for the fact that we have to use brackets and not parenthesis
 92 |   parsedExpression=$(echo "$1" | sed "s/\[/\(/g" | sed "s/\]/\)/g" | grep -Eo "[0-9 + -- / * ^ . a-z A-Z ~ : ( ) ]*") # only grepping valid characters
 93 |   if [ "$parsedExpression" != "$originalEquation" ];then { echo "Error: Expression contains invalid characters"; return 1; }; fi # compare result to original
 94 |   return 0
 95 | }
 96 | 
 97 | encodeEquation()
 98 | {
 99 |   equation=$(echo "$originalEquation" | sed "s:/:(over):g" | sed "s/~/|/g" | sed "s/-/%2D/g") # encode all the special characters
100 | }
101 | 
102 | validateOperation()
103 | {
104 |   operation=$(echo "$1" | tr "[[:upper:]]" "[[:lower:]]") # get rid of case being an issue
105 |   validOp="false" # lets us know if oeration is valid
106 |   for op in "${simpleOperations[@]}"; do # go through all valid simple operations
107 |     if [[ "$op" == "$operation" ]]; then { opType="simple"; validOp="true"; break; }; fi # if the operation matches leave the loop
108 |   done
109 |   if ! $validOp; then { echo "Error: invalid operation, run newton -h to get a list of valid operations"; return 1; }; fi # if not a valid operation error out
110 |   if [[ $operation == "roots" ]]; then operation=zeroes;fi # I gave the ability to use root or zeores but real op is zeroes
111 | }
112 | 
113 | getSimpleResponse()
114 | {
115 |   result=$(httpGet https://newton.now.sh/api/v2/$operation/"$equation" | grep -Eo '"result":"[a-z A-Z 0-9 ( ) \^ / -- + , ]*' | sed s/'"result":"'//g | tr '"' " ") # get reponse, grab result
116 |   if [[ $result == "" ]];then { echo "Error: no result was returned, did you use valid characters?"; return 1; }; fi # if result is empty sometthing went wrong...
117 | }
118 | 
119 | printAnswer()
120 | {
121 |   cat <<EOF
122 | ================================
123 | |Operation: $operation
124 | |Expression: $originalEquation
125 | |Result: $result
126 | ================================
127 | EOF
128 | }
129 | 
130 | 
131 | usage()
132 | {
133 |   cat <<EOF
134 | Newton
135 | Description: Performs numerical calculations all the way up to symbolic math parsing.
136 | Usage: newton [optionalFlags] [operation] [expression] or newton [flag]
137 |   -r  Only print the result, useful for piping output elsewhere
138 |   -u  Update Bash-Snippet Tools
139 |   -h  Show the help
140 |   -v  Get the tool version
141 |  ===================================================
142 | |Operations     Sample Expression      Sample Result|
143 | |---------------------------------------------------|
144 | |Simplify       [[2x^2]+7]*[4x^2]    8 x^4 + 28 x^2 |
145 | |Factor             x^2 + 2x             x (x + 2)  |
146 | |Derive              x^2+2x               2 x + 2   |
147 | |Integrate           x^2+2x         1/3 x^3 + x^2 +C|
148 | |Roots/Zeroes        x^2+2x                2, 0     |
149 | |Tangent             2~x^3              12 x + -16  | (Finding tangent line when x=2 for expression x^3)
150 | |Area               2:4~x^3                 60      | (Finding area under curve from 2 to 4 for expression x^3)
151 | |Cos                   pi                   -1      |
152 | |Sin                   pi                    0      |
153 | |Tan                  pi/4                   1      |
154 | |ArcCos                 1                    0      |
155 | |ArcSin                 0                    0      |
156 | |ArcTan                pi                arcsin(pi) |
157 | |Abs                   -2                    2      |
158 | |Log                   2~8                   3      | (Log base 2 of eight)
159 |  ===================================================
160 | Valid Symbols:
161 |   + add
162 |   - subtract
163 |   [ left parenthesis (you must use brackets bash has a bultin for parenthesis)
164 |   ] right parenthesis (you must use brackets bash has a bultin for parenthesis)
165 |   * multiply
166 |   / divide
167 |   ^ power
168 |   : between the range of left and right side (only for area under curve)
169 |   ~ parameter on right side (only for area, tangent line and log)
170 | EOF
171 | }
172 | 
173 | 
174 | getConfiguredClient || exit 1
175 | 
176 | while getopts "ur:vh" opt; do
177 |   case "$opt" in
178 |     \?) echo "Invalid option: -$OPTARG" >&2
179 |         exit 1
180 |         ;;
181 |     h)  usage
182 |         exit 0
183 |         ;;
184 |     v)  echo "Version $currentVersion"
185 |         exit 0
186 |         ;;
187 |     u)  update
188 |         exit 0
189 |         ;;
190 |     r)  resultOnly="true" && flagCount=$((flagCount + 1 ));;
191 |     :)  echo "Option -$OPTARG requires an argument." >&2
192 |         exit 1
193 |         ;;
194 |   esac
195 | done
196 | 
197 | if [[ $# == "0" ]]; then usage && exit 0
198 | elif [[ $# == "1" ]]; then
199 |   if [[ $1 == "update" ]]; then checkInternet && update && exit 0 || exit 1
200 |   elif [[ $1 == "help" ]]; then usage && exit 0 || exit 1
201 |   else echo "Error: newton needs two arguments, operation and expression" && exit 1;fi
202 | elif [ $# -gt 3 ];then echo "Error: newton only accepts two arguments, operation and expression" && exit 1;fi
203 | 
204 | # flagCount helps us determine what argument to pass to the functions
205 | # flow: validateOperation, validateExpression, encodeEquation, getResponse, print Answer/Result
206 | checkInternet || exit 1
207 | if [[ $flagCount == "0" ]];then validateOperation "$1" || exit 1
208 | elif [[ $flagCount == "1" ]];then validateOperation "$2" || exit 1; fi
209 | if [[ $flagCount == "0" ]];then validateExpression "$2" || exit 1
210 | elif [[ $flagCount == "1" ]];then validateExpression "$3" || exit 1; fi
211 | encodeEquation || exit 1
212 | if [[ $opType == "simple" ]];then getSimpleResponse || exit 1;fi
213 | if [ -z $resultOnly ];then printAnswer
214 | else echo "$result"; fi
215 | 


--------------------------------------------------------------------------------
/newton/newton.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/newton/newton.png


--------------------------------------------------------------------------------
/pwned/pwned:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Navan Chauhan https://github.com/navanchauhan
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | configuredPython=""
  7 | 
  8 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
  9 | getConfiguredClient()
 10 | {
 11 |   if  command -v curl &>/dev/null; then
 12 |     configuredClient="curl"
 13 |   elif command -v wget &>/dev/null; then
 14 |     configuredClient="wget"
 15 |   elif command -v http &>/dev/null; then
 16 |     configuredClient="httpie"
 17 |   elif command -v fetch &>/dev/null; then
 18 |     configuredClient="fetch"
 19 |   else
 20 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 21 |     return 1
 22 |   fi
 23 | }
 24 | 
 25 | ## Allows to call the users configured client without if statements everywhere
 26 | httpGet()
 27 | {
 28 |   case "$configuredClient" in
 29 |     curl)  curl -A curl -s "$@" ;;
 30 |     wget)  wget -qO- "$@" ;;
 31 |     httpie) http -b GET "$@" ;;
 32 |     fetch) fetch -q "$@" ;;
 33 |   esac
 34 | }
 35 | 
 36 | getConfiguredPython()
 37 | {
 38 |   if command -v python3 &>/dev/null; then
 39 |     configuredPython="python3"
 40 |   elif  command -v python2 &>/dev/null; then
 41 |     configuredPython="python2"
 42 |   elif command -v python &>/dev/null; then
 43 |     configuredPython="python"
 44 |   else
 45 |     echo "Error: This tool requires python to be installed."
 46 |     return 1
 47 |   fi
 48 | }
 49 | 
 50 | if [[ $(uname) != "Darwin" ]]; then
 51 |   python()
 52 |   {
 53 |     case "$configuredPython" in
 54 |       python2) python2 "$@" ;;
 55 |       python)  python "$@" ;;
 56 |     esac
 57 |   }
 58 | fi
 59 | 
 60 | checkInternet()
 61 | {
 62 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 63 | }
 64 | 
 65 | ## This function grabs data from Have I been Pwned ? and using python parses it
 66 | ## JSON response to extrapolate the information for storage
 67 | getPwned()
 68 | {
 69 | 	info=$(httpGet  "https://haveibeenpwned.com/api/v2/breachedaccount/$1") > /dev/null #grab the JSON response
 70 |   export PYTHONIOENCODING=utf8 #necessary for python in some cases
 71 |   echo "$info" | python -c "from __future__ import print_function; import sys, json; print(sys.stdin)[0]['Title'])" > /dev/null 2>&1 || { echo "Looks like you have not been breached"; exit 1; } #
 72 |   # The rest of the code is just extrapolating the data with python from the JSON response
 73 |   echo "$info" > .pwned.json
 74 |   title=$(python -c "from __future__ import print_function; import sys, json; print('\n'.join([u['Title']for u in json.load(open(sys.argv[1]))]))" ".pwned.json")
 75 |   rm -f .pwned.json
 76 |   unset info # done with the JSON response not needed anymore
 77 | }
 78 | 
 79 | printPwned()
 80 | {
 81 |   echo
 82 |   echo "============================================="
 83 |   echo "$1 has beeen breached at:"
 84 |   echo "$title"
 85 |   echo "============================================="
 86 |   echo
 87 | }
 88 | 
 89 | 
 90 | update()
 91 | {
 92 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 93 |   # Update utility version 2.2.0
 94 |   # To test the tool enter in the defualt values that are in the examples for each variable
 95 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 96 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 97 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 98 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 99 | 
100 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
101 |     echo "Error: update utility has not been configured correctly." >&2
102 |     exit 1
103 |   elif [[ $latestVersion == "" ]]; then
104 |     echo "Error: no active internet connection" >&2
105 |     exit 1
106 |   else
107 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
108 |       echo "Version $latestVersion available"
109 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
110 |       read -r answer
111 |       if [[ "$answer" == [Yy] ]]; then
112 |         cd ~ || { echo 'Update Failed'; exit 1; }
113 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
114 |         echo -n "Downloading latest version of: $repositoryName."
115 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
116 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
117 |         rm -f .BSnippetsHiddenFile
118 |         echo "Success!"
119 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
120 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
121 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
122 |         ./$nameOfInstallFile "update" || exit 1
123 |         cd ..
124 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
125 |       else
126 |         exit 1
127 |       fi
128 |     else
129 |       echo "$repositoryName is already the latest version"
130 |     fi
131 |   fi
132 | }
133 | 
134 | usage()
135 | {
136 |   cat <<EOF
137 | pwned
138 | Description: Tells you when your account was last breached
139 | Usage: pwned [flag] or pwned [tag]
140 |   -u  Update Bash-Snippet Tools
141 |   -h  Show the help
142 |   -v  Get the tool version
143 | Examples:
144 |   pwned navanchauhan@gmail.com
145 |   pwned navanchauhan@yahoo.com
146 | EOF
147 | }
148 | 
149 | if [[ $(uname) != "Darwin" ]]; then getConfiguredPython || exit 1; fi
150 | getConfiguredClient || exit 1
151 | 
152 | 
153 | while getopts "uvh" opt; do
154 |   case "$opt" in
155 |     \?) echo "Invalid option: -$OPTARG" >&2
156 |         exit 1
157 |         ;;
158 |     h)  usage
159 |         exit 0
160 |         ;;
161 |     v)  echo "Version $currentVersion"
162 |         exit 0
163 |         ;;
164 |     u)  checkInternet || exit 1
165 |         update
166 |         exit 0
167 |         ;;
168 |     :)  echo "Option -$OPTARG requires an argument." >&2
169 |         exit 1
170 |         ;;
171 |   esac
172 | done
173 | 
174 | if [[ $1 == "update" ]]; then
175 |   checkInternet || exit 1
176 |   update
177 |   exit 0
178 | elif [[ $1 == "help" ]]; then
179 |   usage
180 |   exit 0
181 | elif [[ $# == "0" ]]; then
182 |   usage
183 |   exit 0
184 | else
185 |   checkInternet || exit 1
186 |   getPwned "$1" # based on the stock symbol exrapolated by the getTicker function get information on the stock
187 |   printPwned "$1"  # print this information out to the user in a human readable format
188 | exit 0
189 | fi
190 | 


--------------------------------------------------------------------------------
/qrify/qrify:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Linyos Torovoltos github.com/linyostorovovoltos
  3 | 
  4 | currentVersion="1.23.0"
  5 | multiline="0" # flag that indicates multiline option
  6 | fileoutput="0" # flag indicating the -f option
  7 | 
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredClient="wget"
 16 |   elif command -v http &>/dev/null; then
 17 |     configuredClient="httpie"
 18 |   elif command -v fetch &>/dev/null; then
 19 |     configuredClient="fetch"
 20 |   else
 21 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 22 |     return 1
 23 |   fi
 24 | }
 25 | 
 26 | ## Allows to call the users configured client without if statements everywhere
 27 | httpGet()
 28 | {
 29 |   case "$configuredClient" in
 30 |     curl)  curl -A curl -s "$@" ;;
 31 |     wget)  wget -qO- "$@" ;;
 32 |     httpie) http -b GET "$@" ;;
 33 |     fetch) fetch -q "$@" ;;
 34 |   esac
 35 | }
 36 | 
 37 | getConfiguredPython()
 38 | {
 39 |   if command -v python3 &>/dev/null; then
 40 |     configuredPython="python3"
 41 |   elif  command -v python2 &>/dev/null; then
 42 |     configuredPython="python2"
 43 |   elif command -v python &>/dev/null; then
 44 |     configuredPython="python"
 45 |   else
 46 |     echo "Error: This tool requires python to be installed."
 47 |     return 1
 48 |   fi
 49 | }
 50 | 
 51 | if [[ $(uname) != "Darwin" ]]; then
 52 |   python()
 53 |   {
 54 |     case "$configuredPython" in
 55 |       python3) python3 "$@" ;;
 56 |       python2) python2 "$@" ;;
 57 |       python)  python "$@" ;;
 58 |     esac
 59 |   }
 60 | fi
 61 | 
 62 | update()
 63 | {
 64 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 65 |   # Update utility version 2.2.0
 66 |   # To test the tool enter in the defualt values that are in the examples for each variable
 67 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 68 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 69 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 70 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 71 | 
 72 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 73 |     echo "Error: update utility has not been configured correctly." >&2
 74 |     exit 1
 75 |   elif [[ $latestVersion == "" ]]; then
 76 |     echo "Error: no active internet connection" >&2
 77 |     exit 1
 78 |   else
 79 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 80 |       echo "Version $latestVersion available"
 81 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 82 |       read -r answer
 83 |       if [[ "$answer" == [Yy] ]]; then
 84 |         cd ~ || { echo 'Update Failed'; exit 1; }
 85 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 86 |         echo -n "Downloading latest version of: $repositoryName."
 87 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 88 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 89 |         rm -f .BSnippetsHiddenFile
 90 |         echo "Success!"
 91 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 92 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 93 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 94 |         ./$nameOfInstallFile "update" || exit 1
 95 |         cd ..
 96 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 97 |       else
 98 |         exit 1
 99 |       fi
100 |     else
101 |       echo "$repositoryName is already the latest version"
102 |     fi
103 |   fi
104 | }
105 | 
106 | makeqr()
107 | {
108 |   input=$(echo "$input" | sed s/" "/%20/g ) ## replace all spaces in the sentence with HTML-encoded space %20
109 |   httpGet qrenco.de/"$input" ## get a response for the qrcode
110 | }
111 | 
112 | # redirects the image obtained from the goqr api into a png file
113 | makeQRFile() {
114 | 	input=$(echo "$input" | sed -e s/" "/%20/g -e s/'\\n'/%0A/g ) ##same as in the makeqr function
115 | 
116 |   addFileExt
117 | 
118 | 	httpGet "api.qrserver.com/v1/create-qr-code/?size=150x150&data=$input" > "$fileName"
119 | }
120 | 
121 | addFileExt() {
122 |   if ! echo "$fileName" | grep -E -q ".*\.png$|.*\.PNG
quot;
123 |   then
124 |     fileName="$fileName.png"
125 |   fi
126 | }
127 | 
128 | makeMultiLineQr()
129 | {
130 |   if [[ ${configuredClient} != "curl" ]]; then ## prevent usage without curl it is unreliable
131 |     echo "Multiline currently only supports curl!"
132 |     return 1
133 |   else
134 |     input=$(echo "$input" | sed -e s/" "/%20/g -e s/'\\n'/%0A/g ) ##same as in the makeqr function
135 |     printf "%s" "$input"  | curl -F-=\<- qrenco.de
136 |   fi
137 | }
138 | 
139 | # Function to get the json response from POST request
140 | decodeQR() {
141 |   local qrFile="$1"
142 |   if ! echo "$fileName" | grep -E -q ".*\.png$|.*\.PNG$|.*\.gif$|.*\.jpg$|.*\.jpeg$|.*\.GIF$|.*\.JPG$|.*\.JPEG
quot;
143 |   then
144 |     exit 1
145 |   fi
146 | 
147 |   # only uses curl
148 |   # Cannot use wget because it does not support multipart/form-data (as per the man page)]
149 | 
150 |   case "$configuredClient" in
151 |     curl) JSONresponse=$(curl -s -F "file=@$qrFile" http://api.qrserver.com/v1/read-qr-code/) || exit 1;;
152 |     wget) echo "Error:-Not supported with wget" >&2 && exit 1;;
153 |     httpie) JSONresponse=$(http -b --form POST http://api.qrserver.com/v1/read-qr-code/ file@"$qrFile") || exit 1;;
154 |     fetch) echo "Error:-Not supported with wget" >&2 && exit 1;;
155 |   esac
156 | 
157 |   error="$(echo "$JSONresponse" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)[0]['symbol'][0]['error'])")"
158 |   
159 |   if [[ "$error" == "None" ]]
160 |   then
161 |     data="$(echo "$JSONresponse" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)[0]['symbol'][0]['data'])")"
162 |   else
163 |     echo "Error:-$error" >&2 && exit 1
164 |   fi
165 | }
166 | 
167 | checkInternet()
168 | {
169 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
170 | }
171 | 
172 | usage()
173 | {
174 |   cat <<EOF
175 | Qrify
176 | Description: Converts strings or URLs into a QR code.
177 | Usage: qrify [stringtoturnintoqrcode]
178 |     -u  Update Bash-Snippet Tools
179 |     -m  Enable multiline support (feature not working yet)
180 |     -h  Show the help
181 |     -v  Get the tool version
182 |     -f  Store the QR code as a PNG file
183 |     -d  Decode the QR code from a PNG/GIF/JP(E)G file
184 | Examples:
185 |     qrify this is a test string
186 |     qrify -m two\\\\nlines
187 |     qrify github.com (no http:// or https://)
188 |     qrify -f fileoutputName google.com
189 |     qrify -d fileName.png
190 | 
191 | Please pay attention:
192 | This script needs access to an external API.
193 | Do not use it to encode sensitive data.
194 | EOF
195 | }
196 | 
197 | getConfiguredClient || exit 1
198 | 
199 | 
200 | while getopts "d:f:m:hvu*:" option
201 | do
202 |   case "${option}" in
203 |     v) echo "Version $currentVersion" && exit 0 ;;
204 |     u) checkInternet && update && exit 0 || exit 1 ;;
205 |     h) usage && exit 0 ;;
206 |     m) multiline="1" && echo "Error this is not a supported feature yet" && exit 1 ;;
207 | 		f)
208 | 			fileName=$OPTARG
209 | 			#file name is the first argument of the option -f
210 | 			fileoutput="1";;
211 |     d)
212 |       fileName=$OPTARG
213 |       decode="1";;
214 |   esac
215 | done
216 | 
217 | if [[ $# == "0" ]]; then
218 |   usage
219 |   exit 0
220 | elif [[ $# == "1" ]];then
221 |   if [[ $1 == "help" || $1 == ":help" ]]; then
222 |     usage
223 |     exit 0
224 |   elif [[ $1 == "update" ]]; then
225 |     checkInternet || exit 1
226 |     update || exit 1
227 |     exit 0
228 |   else
229 |     getConfiguredPython || exit 1
230 | 	checkInternet || exit 1
231 |     input=$(printf '%s ' "$@")
232 |     makeqr || exit 1
233 |     exit 0
234 |   fi
235 | else
236 |   getConfiguredPython || exit 1
237 |   checkInternet || exit 1
238 |   if [[ $fileoutput == "1" ]]
239 | 	then
240 | 		input=$(printf '%s ' "${@:3}") # first arg is -f, second is the file name, third onwards is the rest of the argument
241 | 		# will have to be changed when implementing multiline QR code
242 | 		makeQRFile || exit 1
243 | 		exit 0
244 |   elif [[ $decode == "1" ]]
245 |   then
246 |     ( decodeQR "$fileName" && echo "$data" ) || exit 1
247 |     exit 0
248 |   elif [[ $multiline == "0" ]]; then
249 |     input=$(printf '%s ' "$@")
250 |     makeqr || exit 1
251 |     exit 0
252 |   else
253 |     input=$(printf '%s ' "${@:2}")
254 |     makeMultiLineQr || exit 1 ## if multiline that means a flag existed so start from the second argument
255 |     exit 0
256 |   fi
257 | fi
258 | 


--------------------------------------------------------------------------------
/qrify/qrify.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/qrify/qrify.png


--------------------------------------------------------------------------------
/short/short:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | configuredPython=""
  7 | 
  8 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
  9 | getConfiguredClient()
 10 | {
 11 |   if  command -v curl &>/dev/null; then
 12 |     configuredClient="curl"
 13 |   elif command -v wget &>/dev/null; then
 14 |     configuredClient="wget"
 15 |   elif command -v http &>/dev/null; then
 16 |     configuredClient="httpie"
 17 |   elif command -v fetch &>/dev/null; then
 18 |     configuredClient="fetch"
 19 |   else
 20 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 21 |     return 1
 22 |   fi
 23 | }
 24 | 
 25 | ## Allows to call the users configured client without if statements everywhere
 26 | httpGet()
 27 | {
 28 |   case "$configuredClient" in
 29 |     curl)  curl -A curl -s "$@" ;;
 30 |     wget)  wget -qO- "$@" ;;
 31 |     httpie) http -b GET "$@" ;;
 32 |     fetch) fetch -q "$@" ;;
 33 |   esac
 34 | }
 35 | 
 36 | checkInternet()
 37 | {
 38 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 39 | }
 40 | 
 41 | update()
 42 | {
 43 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 44 |   # Update utility version 2.2.0
 45 |   # To test the tool enter in the defualt values that are in the examples for each variable
 46 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 47 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 48 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 49 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 50 | 
 51 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 52 |     echo "Error: update utility has not been configured correctly." >&2
 53 |     exit 1
 54 |   elif [[ $latestVersion == "" ]]; then
 55 |     echo "Error: no active internet connection" >&2
 56 |     exit 1
 57 |   else
 58 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 59 |       echo "Version $latestVersion available"
 60 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 61 |       read -r answer
 62 |       if [[ "$answer" == [Yy] ]]; then
 63 |         cd ~ || { echo 'Update Failed'; exit 1; }
 64 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 65 |         echo -n "Downloading latest version of: $repositoryName."
 66 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 67 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 68 |         rm -f .BSnippetsHiddenFile
 69 |         echo "Success!"
 70 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 71 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 72 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 73 |         ./$nameOfInstallFile "update" || exit 1
 74 |         cd ..
 75 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 76 |       else
 77 |         exit 1
 78 |       fi
 79 |     else
 80 |       echo "$repositoryName is already the latest version"
 81 |     fi
 82 |   fi
 83 | }
 84 | 
 85 | usage()
 86 | {
 87 |   cat <<EOF
 88 | Short
 89 | Description: Shorten urls and unmask shortended urls.
 90 | Usage: short [flag] [URL] or short [flag]
 91 |   -s  Shorten the URL
 92 |   -e  Expand a shortened URL
 93 |   -u  Update Bash-Snippet Tools
 94 |   -h  Show the help
 95 |   -v  Get the tool version
 96 | Example:
 97 |    Input:  short tinyurl.com/jhkj
 98 |    Output: http://possiblemaliciouswebsiteornot.com
 99 | EOF
100 | }
101 | 
102 | expandURL()
103 | {
104 |   testURL=$( echo "$1" | cut -c1-8 )
105 |   if [[ $testURL != "https://" ]]; then
106 |     testURL=$( echo "$1" | cut -c1-7 )
107 |     if [[ $testURL != "http://" ]]; then
108 |       url="http://$1"
109 |     else
110 |       url=$1
111 |     fi
112 |   else
113 |     url=$1
114 |   fi
115 |   response=$(httpGet https://unshorten.me/s/"$url")
116 |   errorCheck=$(echo "$response")
117 |   if [[ $errorCheck == "Invalid Short URL" ]]; then
118 |   echo "Error: 404 could not find the website"
119 |   return 1
120 | fi
121 |   returnedURL=$(echo "$response")
122 | }
123 | 
124 | shortenURL()
125 | {
126 | newURL=$1
127 | if [[ $(echo "$1" | grep -Eo "^[h]ttp[s]?://") == "" ]]; then newURL="http://"$1; fi
128 | response=$(httpGet http://tinyurl.com/api-create.php?url="$newURL")
129 | returnedURL=$(echo "$response")
130 | }
131 | 
132 | printResults()
133 | {
134 |   cat <<EOF
135 | =====================================================================
136 | Short URL:    $inputURL
137 | Expanded URL: $returnedURL
138 | =====================================================================
139 | EOF
140 | }
141 | 
142 | printShortenedResults()
143 | {
144 |   cat <<EOF
145 | =====================================================================
146 | Original URL:  $newURL
147 | Shortened URL: $returnedURL
148 | =====================================================================
149 | EOF
150 | }
151 | 
152 | getConfiguredClient || exit 1
153 | 
154 | 
155 | while getopts "e:s:uvh" opt; do
156 |   case "$opt" in
157 |     \?) echo "Invalid option: -$OPTARG" >&2
158 |         exit 1
159 |         ;;
160 |     e)
161 |         expand="true"
162 |         inputURL=$OPTARG
163 |         ;;
164 |     s)
165 |         shorten="true"
166 |         inputURL=$OPTARG
167 |         ;;
168 |     h)  usage
169 |         exit 0
170 |         ;;
171 |     v)  echo "Version $currentVersion"
172 |         exit 0
173 |         ;;
174 |     u)  checkInternet || exit 1
175 |         update
176 |         exit 0
177 |         ;;
178 |     :)  echo "Option -$OPTARG requires an argument." >&2
179 |         exit 1
180 |         ;;
181 |   esac
182 | done
183 | 
184 | if  [[ $expand == "true" && $shorten == "true" ]];then
185 |   echo "Error: the -e and the -s options are mutually exclusive" >&2
186 |   exit 1
187 | fi
188 | 
189 | if [[ $# == 0 ]]; then
190 |   usage
191 |   exit 0
192 | elif [[ $# == "1" ]]; then
193 |   if [[ $1 == "update" ]]; then
194 |     checkInternet || exit 1
195 |     update
196 |   elif [[ $1 == "help" ]]; then
197 |     usage
198 | 
199 |   else
200 |     usage
201 |     exit 1
202 |   fi
203 | elif [[ $expand == "true" ]];then
204 |   checkInternet || exit 1
205 |   expandURL "$inputURL" || exit 1
206 |   printResults
207 | elif [[ $shorten == "true" ]];then
208 |   if [[ $configuredClient != "curl" ]];then
209 |     echo "Error: to shorten URLS you must have curl installed"
210 |   fi
211 |   checkInternet || exit 1
212 |   shortenURL "$inputURL"
213 |   printShortenedResults
214 | else
215 |   echo "Error: short only accepts one argument"
216 |   exit 1
217 | fi
218 | 


--------------------------------------------------------------------------------
/short/short.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/short/short.png


--------------------------------------------------------------------------------
/siteciphers/siteciphers:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | DELAY=1
  3 | configuredClient=""
  4 | currentVersion="1.23.0"
  5 | 
  6 | checkOpenSSL()
  7 | {
  8 |   if  ! command -v openssl &>/dev/null; then
  9 |     echo "Error: to use this tool openssl must be installed" >&2
 10 |     return 1
 11 |   else
 12 |     return 0
 13 |   fi
 14 | }
 15 | 
 16 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 17 | getConfiguredClient()
 18 | {
 19 |   if  command -v curl &>/dev/null; then
 20 |     configuredClient="curl"
 21 |   elif command -v wget &>/dev/null; then
 22 |     configuredClient="wget"
 23 |   elif command -v http &>/dev/null; then
 24 |     configuredClient="httpie"
 25 |   elif command -v fetch &>/dev/null; then
 26 |     configuredClient="fetch"
 27 |   else
 28 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 29 |     return 1
 30 |   fi
 31 | }
 32 | 
 33 | ## Allows to call the users configured client without if statements everywhere
 34 | httpGet()
 35 | {
 36 |   case "$configuredClient" in
 37 |     curl)  curl -A curl -s "$@" ;;
 38 |     wget)  wget -qO- "$@" ;;
 39 |     httpie) http -b GET "$@" ;;
 40 |     fetch) fetch -q "$@" ;;
 41 |   esac
 42 | }
 43 | 
 44 | update()
 45 | {
 46 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 47 |   # Update utility version 2.2.0
 48 |   # To test the tool enter in the defualt values that are in the examples for each variable
 49 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 50 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 51 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 52 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 53 | 
 54 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 55 |     echo "Error: update utility has not been configured correctly." >&2
 56 |     exit 1
 57 |   elif [[ $latestVersion == "" ]]; then
 58 |     echo "Error: no active internet connection" >&2
 59 |     exit 1
 60 |   else
 61 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 62 |       echo "Version $latestVersion available"
 63 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 64 |       read -r answer
 65 |       if [[ "$answer" == [Yy] ]]; then
 66 |         cd ~ || { echo 'Update Failed'; exit 1; }
 67 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 68 |         echo -n "Downloading latest version of: $repositoryName."
 69 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 70 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 71 |         rm -f .BSnippetsHiddenFile
 72 |         echo "Success!"
 73 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 74 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 75 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 76 |         ./$nameOfInstallFile "update" || exit 1
 77 |         cd ..
 78 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 79 |       else
 80 |         exit 1
 81 |       fi
 82 |     else
 83 |       echo "$repositoryName is already the latest version"
 84 |     fi
 85 |   fi
 86 | }
 87 | 
 88 | usage()
 89 | {
 90 |   cat <<EOF
 91 | Siteciphers
 92 | Description: Checks the available ciphers for the SSL of an https site.
 93 | Usage: siteciphers [flag] or siteciphers [optionalDFlag] [website]
 94 |   -u  Update Bash-Snippet Tools
 95 |   -h  Show the help
 96 |   -v  Get the tool version
 97 |   -d  Set the delay between requests sent to the site (default is 1 sec)
 98 | Examples:
 99 |   siteciphers github.com
100 |   siteciphers -d 0.5 github.com
101 | EOF
102 | }
103 | 
104 | checkInternet()
105 | {
106 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
107 | }
108 | 
109 | checkCiphers()
110 | {
111 |   ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g') # grab all ciphers
112 |   SERVER=$1:443 # setup the connection server
113 |   for cipher in ${ciphers[*]}; do # for all possible ciphers
114 |     result=$(echo | openssl s_client -cipher "$cipher" -connect "$SERVER" 2>&1)
115 |     if [[ "$result" =~ ":error:" ]]; then
116 |       if [[ -z $2 ]]; then
117 |         error=$(echo -n "$result" | cut -d':' -f6)
118 |         echo "$cipher - NO ($error)"
119 |       fi
120 |     else
121 |       if [[ "$result" =~ "Cipher is $cipher" || "$result" =~ "Cipher    :" ]]; then
122 |         echo "$cipher - YES"
123 |       else
124 |         if [[ -z $2 ]]; then
125 |           echo "$cipher - UNKNOWN RESPONSE - $result"
126 |         fi
127 |       fi
128 |     fi
129 |     sleep $DELAY # sleep as to not overload the requests to the server
130 |   done
131 | }
132 | 
133 | checkOpenSSL || exit 1
134 | getConfiguredClient || exit 1
135 | 
136 | 
137 | if [[ $# == "0" ]]; then
138 |   usage
139 |   exit 1
140 | elif [[ $1 == "update" ]]; then
141 |   checkInternet || exit 1
142 |   update
143 |   exit 0
144 | elif [[ $1 == "help" ]]; then
145 |   usage
146 |   exit 0
147 | fi
148 | 
149 | while getopts "huvd:" opt; do ## alows for using options in bash
150 |   case "$opt" in
151 |     \?) echo "Invalid option: -$OPTARG" >&2
152 |         exit 1
153 |         ;;
154 |     d)  #set the delay with the -d option
155 |         DELAY=$OPTARG
156 |         dFlag="1"
157 |         ;;
158 |     u)  checkInternet || exit 1
159 |         update
160 |         exit 0
161 |         ;;
162 |     h)  usage
163 |         exit 0
164 |         ;;
165 |     v)  echo "Version $currentVersion"
166 |         exit 0
167 |         ;;
168 |     :)  ## will run when no arguments are provided to to d options
169 |         echo "Option -$OPTARG requires an argument." >&2
170 |         exit 1
171 |         ;;
172 |   esac
173 | done
174 | 
175 | checkInternet || exit 1
176 | if [[ $dFlag == "1" ]]; then
177 |   checkCiphers "$3" || exit 1 # if dflag is present input will look like siteciphers -d 0.5 github.com making the website the third arg
178 | else
179 |   checkCiphers "$1" || exit 1
180 | fi
181 | 


--------------------------------------------------------------------------------
/siteciphers/siteciphers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/siteciphers/siteciphers.png


--------------------------------------------------------------------------------
/skeleton:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | currentVersion="1.23.0"
  4 | configuredClient=""
  5 | 
  6 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
  7 | getConfiguredClient()
  8 | {
  9 |   if  command -v curl &>/dev/null; then
 10 |     configuredClient="curl"
 11 |   elif command -v wget &>/dev/null; then
 12 |     configuredClient="wget"
 13 |   elif command -v http &>/dev/null; then
 14 |     configuredClient="httpie"
 15 |   elif command -v fetch &>/dev/null; then
 16 |     configuredClient="fetch"
 17 |   else
 18 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 19 |     return 1
 20 |   fi
 21 | }
 22 | 
 23 | # The python and JSON functions can be deleted if the script does not need them
 24 | 
 25 | ## This function determines which version of python is installed on the machine
 26 | getConfiguredPython()
 27 | {
 28 |   if command -v python3 &>/dev/null; then
 29 |     configuredPython="python3"
 30 |   elif  command -v python2 &>/dev/null; then
 31 |     configuredPython="python2"
 32 |   elif command -v python &>/dev/null; then
 33 |     configuredPython="python"
 34 |   else
 35 |     echo "Error: This tool requires python to be installed."
 36 |     return 1
 37 |   fi
 38 | }
 39 | 
 40 | ## Don't alter the python call if it's coming from a Mac
 41 | if [[ $(uname) != "Darwin" ]]; then
 42 |   python()
 43 |   {
 44 |     case "$configuredPython" in
 45 |       python3) python3 "$@" ;;
 46 |       python2) python2 "$@" ;;
 47 |       python)  python "$@" ;;
 48 |     esac
 49 |   }
 50 | fi
 51 | 
 52 | ## Grabs an element from a a json string and then echoes it to stdout
 53 | ## $1 = the JSON string
 54 | ## $n+1 = the elements to be indexed
 55 | AccessJsonElement() {
 56 |   json="$1"
 57 |   shift
 58 |   accessor=""
 59 |   for element in "$@"; do
 60 |       accessor="${accessor}['$element']"
 61 |   done
 62 |   echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})"
 63 |   return "$?"
 64 | }
 65 | 
 66 | ## Allows to call the users configured client without if statements everywhere
 67 | httpGet()
 68 | {
 69 |   case "$configuredClient" in
 70 |     curl)  curl -A curl -s "$@" ;;
 71 |     wget)  wget -qO- "$@" ;;
 72 |     httpie) http -b GET "$@" ;;
 73 |     fetch) fetch -q "$@" ;;
 74 |   esac
 75 | }
 76 | 
 77 | update()
 78 | {
 79 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 80 |   # Update utility version 1.2.0
 81 |   # To test the tool enter in the default values that are in the examples for each variable
 82 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 83 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 84 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 85 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 86 | 
 87 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 88 |     echo "Error: update utility has not been configured correctly." >&2
 89 |     exit 1
 90 |   elif [[ $latestVersion == "" ]]; then
 91 |     echo "Error: no active internet connection" >&2
 92 |     exit 1
 93 |   else
 94 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 95 |       echo "Version $latestVersion available"
 96 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 97 |       read -r answer
 98 |       if [[ "$answer" == [Yy] ]]; then
 99 |         cd ~ || { echo 'Update Failed'; exit 1; }
100 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
101 |         git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; }
102 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
103 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
104 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
105 |         ./$nameOfInstallFile "update" || exit 1
106 |         cd ..
107 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
108 |       else
109 |         exit 1
110 |       fi
111 |     else
112 |       echo "$repositoryName is already the latest version"
113 |     fi
114 |   fi
115 | }
116 | 
117 | checkInternet()
118 | {
119 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
120 | }
121 | 
122 | usage()
123 | {
124 |   cat <<EOF
125 | Skeleton
126 | Description: Short desciption of the tool.
127 | Usage: tool [flags] or tool [flags] [arguments]
128 |   -u  Update Bash-Snippet Tools
129 |   -h  Show the help
130 |   -v  Get the tool version
131 | Examples:
132 |    tool
133 |    tool
134 | EOF
135 | }
136 | 
137 | 
138 | 
139 | while getopts "uvh" opt; do
140 |   case "$opt" in
141 |     \?) echo "Invalid option: -$OPTARG" >&2
142 |         exit 1
143 |         ;;
144 |     h)  usage
145 |         exit 0
146 |         ;;
147 |     v)  echo "Version $currentVersion"
148 |         exit 0
149 |         ;;
150 |     u)  getConfiguredClient || exit 1
151 |         checkInternet || exit 1
152 |         update
153 |         exit 0
154 |         ;;
155 |     :)  echo "Option -$OPTARG requires an argument." >&2
156 |         exit 1
157 |         ;;
158 |   esac
159 | done
160 | 
161 | # special set of first arguments that have a specific behavior across tools
162 | if [[ $# == "0" ]]; then
163 |   usage ## if calling the tool with no flags and args chances are you want to return usage
164 |   exit 0
165 | elif [[ $# == "1" ]]; then
166 |   if [[ $1 == "update" ]]; then
167 |     getConfiguredClient || exit 1
168 |     checkInternet || exit 1
169 |     update || exit 1
170 |     exit 0
171 |   elif [[ $1 == "help" ]]; then
172 |     usage
173 |     exit 0
174 |   fi
175 | fi
176 | 
177 | ## The rest of the conditions and code would go here
178 | ## Make sure to use checkInternet at least once before any time httpGet will be called.
179 | ## Make sure to call getConfiguredClient at least once before ever calling checkInternet.
180 | ## Make sure to call getConfiguredPython at least once before trying to pipeout to python directly or using AccessJsonElement


--------------------------------------------------------------------------------
/skeleton.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | export TOOL_NAME='skeleton'
 4 | 
 5 | setup() {
 6 |   # $REPO_DIR/tests/skeleton.bats
 7 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 8 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 9 | }
10 | 
11 | @test "Testing ${TOOL_NAME} tool" {
12 |   echo "${TOOL_NAME}"
13 | }
14 | 
15 | @test "Confirm the \$REPO_DIR variable is evaluated" {
16 |   cd "${REPO_DIR}" && pwd
17 |   [[ "$status" -eq 0 ]]
18 | }
19 | 
20 | @test "Change into the tool directory for ${TOOL_NAME}" {
21 |   cd "${TOOL_DIR}" && pwd
22 |   [[ "$status" -eq 0 ]]
23 | }
24 | 
25 | @test "Check for latest version of bash-snippets on update" {
26 |   if [[ "$(uname)" == "Linux" ]]; then
27 |     run "${TOOL_DIR}/${TOOL_NAME}" update
28 |     [[ "$status" -eq 0 ]]
29 |     [ "$output" == "Bash-Snippets is already the latest version" ]
30 |   fi
31 | }
32 | 
33 | @test "The -h option should print usage" {
34 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
35 |   [[ "$status" -eq 0 ]]
36 |   # if bash is less than 7 yrs old
37 |   if ((${BASH_VERSINFO[0]} >= 4)); then
38 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
39 |   else
40 |     # or im probably a stoneage mac
41 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
42 |   fi
43 | }
44 | 
45 | @test "No arguments prints usage instructions" {
46 |   run "${TOOL_DIR}/${TOOL_NAME}"
47 |   [[ "$status" -eq 0 ]]
48 |   # if bash is less than 7 yrs old
49 |   if ((${BASH_VERSINFO[0]} >= 4)); then
50 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
51 |   else
52 |     # or im probably a stoneage mac
53 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
54 |   fi
55 | }
56 | 
57 | @test "Get the tools version with -v" {
58 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
59 |   [[ "$status" -eq 0 ]]
60 |   expected='Version'
61 |   [[ "${output}" =~ "${expected}" ]]
62 | }
63 | 
64 | 
65 | # Tool specific tests
66 | @test "Do that cool thing" {
67 |   run "${TOOL_DIR}/${TOOL_NAME}" cool
68 |   [[ "$status" -eq 0 ]]
69 |   expected='This is awesome'
70 |   [[ "${output}" =~ "${expected}" ]]
71 | }
72 | 
73 | @test "Testing coolness factor" {
74 |   run "${TOOL_DIR}/${TOOL_NAME}" cool --even-cooler
75 |   [[ "$status" -eq 0 ]]
76 |   expected='subzero'
77 |   [[ "printf '%s\n' ${lines[1]}" =~ "${expected}" ]]
78 | }
79 | 
80 | 


--------------------------------------------------------------------------------
/stocks/stocks:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | # Author: Navan Chauhan https://github.com/navanchauhan
  4 | # Author: Tyler Stubenvoll https://github.com/tjstub
  5 | 
  6 | currentVersion="1.23.0"
  7 | configuredClient=""
  8 | configuredPython=""
  9 | 
 10 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 11 | getConfiguredClient()
 12 | {
 13 |   if  command -v curl &>/dev/null; then
 14 |     configuredClient="curl"
 15 |   elif command -v wget &>/dev/null; then
 16 |     configuredClient="wget"
 17 |   elif command -v http &>/dev/null; then
 18 |     configuredClient="httpie"
 19 |   elif command -v fetch &>/dev/null; then
 20 |     configuredClient="fetch"
 21 |   else
 22 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 23 |     return 1
 24 |   fi
 25 | }
 26 | 
 27 | ## Allows to call the users configured client without if statements everywhere
 28 | httpGet()
 29 | {
 30 |   case "$configuredClient" in
 31 |     curl)  curl -A curl -s "$@" ;;
 32 |     wget)  wget -qO- "$@" ;;
 33 |     httpie) http -b GET "$@" ;;
 34 |     fetch) fetch -q "$@" ;;
 35 |   esac
 36 | }
 37 | 
 38 | getConfiguredPython()
 39 | {
 40 |   if command -v python3 &>/dev/null; then
 41 |     configuredPython="python3"
 42 |   elif  command -v python2 &>/dev/null; then
 43 |     configuredPython="python2"
 44 |   elif command -v python &>/dev/null; then
 45 |     configuredPython="python"
 46 |   else
 47 |     echo "Error: This tool requires python to be installed."
 48 |     return 1
 49 |   fi
 50 | }
 51 | 
 52 | if [[ $(uname) != "Darwin" ]]; then
 53 |   python()
 54 |   {
 55 |     case "$configuredPython" in
 56 |       python3) python3 "$@" ;;
 57 |       python2) python2 "$@" ;;
 58 |       python)  python "$@" ;;
 59 |     esac
 60 |   }
 61 | fi
 62 | 
 63 | checkInternet()
 64 | {
 65 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 66 | }
 67 | 
 68 | ## Grabs an element from a a json string and then echoes it to stdout
 69 | ## $1 = the JSON string
 70 | ## $n+1 = the elements to be indexed
 71 | AccessJsonElement() {
 72 |   json="$1"
 73 |   shift
 74 |   accessor=""
 75 |   for element in "$@"; do
 76 |       accessor="${accessor}['$element']"
 77 |   done
 78 |   echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})"
 79 |   return "$?"
 80 | }
 81 | 
 82 | ## This function grabs information about a stock and prints it for consumption
 83 | printStockInformation()
 84 | {
 85 |   # this data is updated hourly.
 86 |   stockProfile="$(httpGet "https://financialmodelingprep.com/api/v3/company/profile/${1}")" > /dev/null
 87 |   # this is realtime data.
 88 |   stockPrice="$(httpGet "https://financialmodelingprep.com/api/v3/stock/real-time-price/${1}")" > /dev/null
 89 |   # necessary for python in some cases
 90 |   export PYTHONIOENCODING=utf8
 91 |   # checking if we get any information back from the server if not 
 92 |   # chances are it isnt a valid stock symbol
 93 |   AccessJsonElement "$stockProfile" "profile" "companyName" > /dev/null 2>&1 \
 94 |     || { echo "$1: Not a valid stock symbol"; exit 1; } 
 95 |   # The rest of the code is just extrapolating the data with python 
 96 |   # from the JSON response
 97 |   name="$(AccessJsonElement "$stockProfile" "profile" "companyName")"
 98 |   exchangeName="$(AccessJsonElement "$stockProfile" "profile" "exchange")"
 99 |   latestPrice="$(AccessJsonElement "$stockPrice" "price")"
100 |   range="$(AccessJsonElement "$stockProfile" "profile" "range")"
101 |   priceChange="$(AccessJsonElement "$stockProfile" "profile" "changes")"
102 |   priceChangePercentage="$(AccessJsonElement "$stockProfile" "profile" "changesPercentage")"
103 |   volumeAvg="$(AccessJsonElement "$stockProfile" "profile" "volAvg")"
104 | 
105 |   cat <<EOF
106 | 
107 | ==============================================
108 | | $name -- Stock Information
109 | ==============================================
110 | | Stock Details
111 | |   * symbol: $1
112 | |   * Exchange: $exchangeName
113 | | Real time data
114 | |   * Latest Price: $latestPrice
115 | | Hourly data
116 | |   * 52 week range: $range
117 | |   * Price Change: $priceChange
118 | |   * PriceChangePercent: $priceChangePercentage
119 | |   * Volume average: $volumeAvg
120 | ==============================================
121 | EOF
122 | 
123 | }
124 | 
125 | ## This function queries yahoo to determine the stock ticker for a certain company
126 | ## this allows the usage of stocks to be extended where now you can enter stocks appple
127 | ## and it will determine the stock symbol for apple is AAPL and move on from there
128 | getTicker()
129 | {
130 |   input="$(echo "$@" | tr " " +)"
131 |   response="$(httpGet "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=$input&region=1&lang=en%22")" > /dev/null
132 |   # using python to extrapolate the stock symbol
133 |   symbol="$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['ResultSet']['Result'][0]['symbol'])")"
134 |   # just unsets the entire response after using it since all I need is the stock ticker
135 |   unset response 
136 | }
137 | 
138 | update()
139 | {
140 |   # Author: Alexander Epstein https://github.com/alexanderepstein
141 |   # Update utility version 2.2.0
142 |   # To test the tool enter in the defualt values that are in the examples for each variable
143 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
144 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
145 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
146 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
147 | 
148 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
149 |     echo "Error: update utility has not been configured correctly." >&2
150 |     exit 1
151 |   elif [[ $latestVersion == "" ]]; then
152 |     echo "Error: no active internet connection" >&2
153 |     exit 1
154 |   else
155 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
156 |       echo "Version $latestVersion available"
157 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
158 |       read -r answer
159 |       if [[ "$answer" == [Yy] ]]; then
160 |         cd ~ || { echo 'Update Failed'; exit 1; }
161 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
162 |         echo -n "Downloading latest version of: $repositoryName."
163 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
164 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
165 |         rm -f .BSnippetsHiddenFile
166 |         echo "Success!"
167 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
168 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
169 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
170 |         ./$nameOfInstallFile "update" || exit 1
171 |         cd ..
172 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
173 |       else
174 |         exit 1
175 |       fi
176 |     else
177 |       echo "$repositoryName is already the latest version"
178 |     fi
179 |   fi
180 | }
181 | 
182 | usage()
183 | {
184 |   cat <<EOF
185 | Stocks
186 | Description: Finds the latest information on a certain stock.
187 | Usage: stocks [flag] or stocks [company/ticker]
188 |   -u  Update Bash-Snippet Tools
189 |   -h  Show the help
190 |   -v  Get the tool version
191 | Examples:
192 |   stocks AAPL
193 |   stocks Tesla
194 | EOF
195 | }
196 | 
197 | if [[ $(uname) != "Darwin" ]]; then getConfiguredPython || exit 1; fi
198 | getConfiguredClient || exit 1
199 | 
200 | 
201 | while getopts "uvh" opt; do
202 |   case "$opt" in
203 |     \?) echo "Invalid option: -$OPTARG" >&2
204 |         exit 1
205 |         ;;
206 |     h)  usage
207 |         exit 0
208 |         ;;
209 |     v)  echo "Version $currentVersion"
210 |         exit 0
211 |         ;;
212 |     u)  checkInternet || exit 1
213 |         update
214 |         exit 0
215 |         ;;
216 |     :)  echo "Option -$OPTARG requires an argument." >&2
217 |         exit 1
218 |         ;;
219 |   esac
220 | done
221 | 
222 | if [[ $1 == "update" ]]; then
223 |   checkInternet || exit 1
224 |   update
225 |   exit 0
226 | elif [[ $1 == "help" ]]; then
227 |   usage
228 |   exit 0
229 | elif [[ $# == "0" ]]; then
230 |   usage
231 |   exit 0
232 | else
233 |   checkInternet || exit 1
234 |   # the company name might have spaces so passing in all args allows for this
235 |   getTicker "$@"
236 |   # based on the stock symbol exrapolated by the getTicker function get 
237 |   # information on the stock
238 |   printStockInformation "$symbol"
239 |   exit 0
240 | fi
241 | 
242 | 


--------------------------------------------------------------------------------
/stocks/stocks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/stocks/stocks.png


--------------------------------------------------------------------------------
/taste/taste.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/taste/taste.png


--------------------------------------------------------------------------------
/tests/bak2dvd.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | #
 3 | export TOOL_NAME='bak2dvd'
 4 | 
 5 | setup() {
 6 |   # $REPO_DIR/tests/bak2dvd.bats
 7 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 8 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 9 | }
10 | 
11 | @test "Testing ${TOOL_NAME} tool" {
12 |   echo "${TOOL_NAME}"
13 | }
14 | 
15 | @test "Confirm the \$REPO_DIR variable is evaluated" {
16 |   cd "${REPO_DIR}" && pwd
17 |   
18 |   [[ "$status" -eq 0 ]]
19 | }
20 | 
21 | # can cd into script dir
22 | @test "Confirm a valid directory for ${TOOL_NAME}" {
23 |   cd "${TOOL_DIR}" && pwd
24 |   
25 |   [[ "$status" -eq 0 ]]
26 | }
27 | 
28 | @test "Check for latest version of bash-snippets on update" {
29 |   if [[ "$(uname)" == "Linux" ]]; then
30 |     run "${TOOL_DIR}/${TOOL_NAME}" update
31 |   
32 |     [[ "$status" -eq 0 ]]
33 |     [ "$output" == "Bash-Snippets is already the latest version" ]
34 |   fi
35 | }
36 | 
37 | @test "The -h option should print usage" {
38 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
39 |   
40 |   [[ "$status" -eq 0 ]]
41 |   # if bash is less than 7 yrs old
42 |   if ((${BASH_VERSINFO[0]} >= 4)); then
43 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
44 |   else
45 |     # or im probably a stoneage mac
46 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
47 |   fi
48 | }
49 | 
50 | @test "No arguments prints usage instructions" {
51 |   run "${TOOL_DIR}/${TOOL_NAME}"
52 |   
53 |   [[ "$status" -eq 0 ]]
54 |   # if bash is less than 7 yrs old
55 |   if ((${BASH_VERSINFO[0]} >= 4)); then
56 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
57 |   else
58 |     # or im probably a stoneage mac
59 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
60 |   fi
61 | }
62 | 
63 | @test "Get the tools version with -v" {
64 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
65 |   
66 |   [[ "$status" -eq 0 ]]
67 |   expected='Version'
68 |   [[ "${output}" =~ "${expected}" ]]
69 | }
70 | 
71 | # Tool specific tests
72 | 
73 | 


--------------------------------------------------------------------------------
/tests/cheat.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | export TOOL_NAME='cheat'
 4 | 
 5 | setup() {
 6 |   # $REPO_DIR/tests/tool.bats
 7 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 8 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 9 | }
10 | 
11 | @test "Testing ${TOOL_NAME} tool" {
12 |   echo "${TOOL_NAME}"
13 | }
14 | 
15 | @test "Confirm the \$REPO_DIR variable is evaluated" {
16 |   cd "${REPO_DIR}" && pwd
17 |   
18 |   [[ "$status" -eq 0 ]]
19 | }
20 | 
21 | # can cd into script dir
22 | @test "Confirm a valid directory for ${TOOL_NAME}" {
23 |   cd "${TOOL_DIR}" && pwd
24 |   
25 |   [[ "$status" -eq 0 ]]
26 | }
27 | 
28 | @test "Check for latest version of bash-snippets on update" {
29 |   if [[ "$(uname)" == "Linux" ]]; then
30 |     run "${TOOL_DIR}/${TOOL_NAME}" update
31 |   
32 |     [[ "$status" -eq 0 ]]
33 |     [ "$output" == "Bash-Snippets is already the latest version" ]
34 |   fi
35 | }
36 | 
37 | @test "The -h option should print usage" {
38 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
39 |   
40 |   [[ "$status" -eq 0 ]]
41 |   # if bash is less than 7 yrs old
42 |   if ((${BASH_VERSINFO[0]} >= 4)); then
43 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
44 |   else
45 |     # or im probably a stoneage mac
46 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
47 |   fi
48 | }
49 | 
50 | @test "No arguments prints usage instructions" {
51 |   run "${TOOL_DIR}/${TOOL_NAME}"
52 |   
53 |   [[ "$status" -eq 0 ]]
54 |   # if bash is less than 7 yrs old
55 |   if ((${BASH_VERSINFO[0]} >= 4)); then
56 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
57 |   else
58 |     # or im probably a stoneage mac
59 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
60 |   fi
61 | }
62 | 
63 | @test "Get the tools version with -v" {
64 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
65 |   
66 |   [[ "$status" -eq 0 ]]
67 |   expected='Version'
68 |   [[ "${output}" =~ "${expected}" ]]
69 | }
70 | 
71 | @test "Grabbing information on a programming language (rust)" {
72 |   run "${TOOL_DIR}/${TOOL_NAME}" rust
73 |   [[ "$status" -eq 0 ]]
74 |   [[ "${lines[0]}" =~ 'Rust is a systems' ]]
75 | }
76 | 
77 | @test "Testing unkown topic due to misspelling" {
78 |   run "${TOOL_DIR}/${TOOL_NAME}" suuuper thiingsa
79 |   [[ "$status" -eq 0 ]]
80 |   [[ "printf '%s\n' ${lines[1]}" =~ 'Unknown' ]]
81 | }
82 | 


--------------------------------------------------------------------------------
/tests/cloudup.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing cloudup tool" {
 4 |    echo cloudup
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run cloudup update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run cloudup -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Cloudup" ]
19 | }
20 | 
21 | @test "Get the tools version with -v" {
22 |   run cloudup -v
23 |   [ "$status" -eq 0 ]
24 |   result=$( echo $(cloudup -v) | grep -Eo "Version")
25 |   [ "$result" = "Version" ]
26 | }
27 | 


--------------------------------------------------------------------------------
/tests/crypt.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing crypt tool" {
 4 |    echo crypt
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run crypt update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run crypt -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Crypt" ]
19 | }
20 | 
21 | @test "No arguments prints usage instructions" {
22 |   run crypt
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "Crypt" ]
25 | }
26 | 
27 | 
28 | @test "Get the tools version with -v" {
29 |   run crypt -v
30 |   [ "$status" -eq 0 ]
31 |   result=$( echo $(crypt -v) | grep -Eo "Version")
32 |   [ "$result" = "Version" ]
33 | }
34 | 


--------------------------------------------------------------------------------
/tests/cryptocurrency.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing cryptocurrency tool" {
 4 |    echo cryptocurrency
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run cryptocurrency update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run cryptocurrency -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "CryptoCurrency" ]
19 | }
20 | 
21 | @test "Get the tools version with -v" {
22 |   run cryptocurrency -v
23 |   [ "$status" -eq 0 ]
24 |   result=$( echo $(cryptocurrency -v) | grep -Eo "Version")
25 |   [ "$result" = "Version" ]
26 | }
27 | 


--------------------------------------------------------------------------------
/tests/currency.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing currency tool" {
 4 |    echo currency
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run currency update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run currency -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Currency" ]
19 | }
20 | 
21 | @test "Testing currency exchange (12.35 EUR TO USD)" {
22 |   run currency EUR USD 12.35
23 |   [ "$status" -eq 0 ]
24 |   ##[ "${lines[0]}" = "=========================" ]
25 |   ##[ "${lines[1]}" = "| EUR to USD" ]
26 |   ##[ "${lines[3]}" = "| EUR: 12.35" ]
27 | }
28 | 
29 | @test "Get the tools version with -v" {
30 |   run currency -v
31 |   [ "$status" -eq 0 ]
32 |   result=$( echo $(currency -v) | grep -Eo "Version")
33 |   [ "$result" = "Version" ]
34 | }
35 | 


--------------------------------------------------------------------------------
/tests/geo.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing geo tool" {
 4 |    echo geo
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run geo update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run geo -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Geo" ]
19 | }
20 | 
21 | @test "Get the tools version with -v" {
22 |   run geo -v
23 |   [ "$status" -eq 0 ]
24 |   result=$( echo $(geo -v) | grep -Eo "Version")
25 |   [ "$result" = "Version" ]
26 | }
27 | 


--------------------------------------------------------------------------------
/tests/gist.bats:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bats
  2 | 
  3 | export TOOL_NAME='gist'
  4 | export GIST_USER='phamhsieh'
  5 | export GIST_API_TOKEN='dd43dc9949a5b4a1d6c7''b779f13af357282016e4'
  6 | 
  7 | setup() {
  8 |   # $REPO_DIR/tests/taste.bats
  9 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 10 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 11 | }
 12 | 
 13 | @test "Testing ${TOOL_NAME} tool" {
 14 |   echo "${TOOL_NAME}"
 15 | }
 16 | 
 17 | @test "Get the tools version with command version" {
 18 |   run "${TOOL_DIR}/${TOOL_NAME}" version
 19 |   [ "$status" -eq 0 ]
 20 |   result=$( echo $(${TOOL_DIR}/${TOOL_NAME} version) | grep -Eo "Version")
 21 |   [ "$result" = "Version" ]
 22 | }
 23 | 
 24 | @test "Check for latest version of bash-snippets on update" {
 25 |   if [[ "$(uname)" == "Linux" ]]; then
 26 |     run "${TOOL_DIR}/${TOOL_NAME}" update
 27 | 
 28 |     [[ "$status" -eq 0 ]]
 29 |     [ "$output" == "Bash-Snippets is already the latest version" ]
 30 |   fi
 31 | }
 32 | 
 33 | @test "The help command should print usage" {
 34 |   run "${TOOL_DIR}/${TOOL_NAME}" help
 35 | 
 36 |   [[ "$status" -eq 0 ]]
 37 |   [[ "${lines[0]}" = "${TOOL_NAME}" ]]
 38 | }
 39 | 
 40 | @test "Use config command to add configuarion for user" {
 41 |   run "${TOOL_DIR}/${TOOL_NAME}" config user ${GIST_USER}
 42 |   [ "$status" -eq 0 ]
 43 |   [ "${lines[-1]}" = "user=${GIST_USER}" ]
 44 | }
 45 | 
 46 | @test "Use config command to add configuarion for token" {
 47 |   run "${TOOL_DIR}/${TOOL_NAME}" config token ${GIST_API_TOKEN}
 48 |   [ "$status" -eq 0 ]
 49 |   [ "${lines[-1]}" = "token=${GIST_API_TOKEN}" ]
 50 | }
 51 | 
 52 | @test "The new command should create a new public gist with gist command" {
 53 |   hint=false run "${TOOL_DIR}/${TOOL_NAME}" new --file gist --desc 'Manage gist like a pro' "${TOOL_DIR}/${TOOL_NAME}"
 54 |   [ "$status" -eq 0 ]
 55 |   [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]]
 56 | }
 57 | 
 58 | @test "The fetch command should fetch user gists" {
 59 |   hint=false run "${TOOL_DIR}/${TOOL_NAME}" fetch
 60 |   [ "$status" -eq 0 ]
 61 |   [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]]
 62 | }
 63 | 
 64 | @test "The fetch command should fetch starred gists" {
 65 |   hint=false run "${TOOL_DIR}/${TOOL_NAME}" fetch star
 66 |   [ "$status" -eq 0 ]
 67 |   echo ${lines[-1]}
 68 |   [[ "${lines[-1]}" =~ (Not a single valid gist|^ *s[0-9]+ +https://gist.github.com/[0-9a-z]+) ]]
 69 | }
 70 | 
 71 | @test "No arguments prints the list of gists" {
 72 |   hint=false run "${TOOL_DIR}/${TOOL_NAME}"
 73 |   [ "$status" -eq 0 ]
 74 |   [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]]
 75 | }
 76 | 
 77 | @test "Specify an index to return the path of cloned repo" {
 78 |   run "${TOOL_DIR}/${TOOL_NAME}" 1 --no-action
 79 |   [ "$status" -eq 0 ]
 80 |   [[ "${lines[-1]}" =~ (${HOME}/gist/[0-9a-z]+) ]]
 81 | }
 82 | 
 83 | @test "The edit command should modify the description of a gist" {
 84 |   "${TOOL_DIR}/${TOOL_NAME}" edit 1 "Modified description"
 85 |   run "${TOOL_DIR}/${TOOL_NAME}" detail 1
 86 |   [ "$status" -eq 0 ]
 87 |   [[ "${lines[0]}" =~ (Modified description$) ]]
 88 | }
 89 | 
 90 | @test "The delete command should delete specified gists" {
 91 |   run "${TOOL_DIR}/${TOOL_NAME}" delete 1 --force
 92 |   [ "$status" -eq 0 ]
 93 |   [ "${lines[0]}" = '1 deleted' ]
 94 | }
 95 | 
 96 | @test "The user command should get the list of public gists from a user" {
 97 |   run "${TOOL_DIR}/${TOOL_NAME}" user defunkt
 98 |   [ "$status" -eq 0 ]
 99 |   [[ "${lines[0]}" =~ (https://gist.github.com/[0-9a-z]+ defunkt) ]]
100 | }
101 | 


--------------------------------------------------------------------------------
/tests/meme.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing meme tool" {
 4 |    echo meme
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run meme update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run meme -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Meme" ]
19 | }
20 | 
21 | 
22 | 
23 | @test "Get the tools version with -v" {
24 |   run meme -v
25 |   [ "$status" -eq 0 ]
26 |   result=$( echo $(meme -v) | grep -Eo "Version")
27 |   [ "$result" = "Version" ]
28 | }
29 | 


--------------------------------------------------------------------------------
/tests/movies.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing movies tool" {
 4 |    echo movies
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run movies update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run movies -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Movies" ]
19 | }
20 | 
21 | @test "No arguments prints usage instructions" {
22 |   run movies
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "Movies" ]
25 | }
26 | 
27 | @test "Get information on a single movie" {
28 |   run movies Argo
29 |   [ "$status" -eq 0 ]
30 |   [ "${lines[0]}" = "+=====================================================+" ]
31 |   [ "${lines[1]}" = "|      Title: Argo                                    |" ]
32 | }
33 | 
34 | 
35 | 
36 | @test "Get the tools version with -v" {
37 |   run movies -v
38 |   [ "$status" -eq 0 ]
39 |   result=$( echo $(movies -v) | grep -Eo "Version")
40 |   [ "$result" = "Version" ]
41 | }
42 | 


--------------------------------------------------------------------------------
/tests/newton.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing newton tool" {
 4 |    echo newton
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run newton update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run newton -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Newton" ]
19 | }
20 | 
21 | @test "Testing newton simplify for [[2x^2]+7]*[4x^2]" {
22 |   run newton simplify [[2x^2]+7]*[4x^2]
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "================================" ]
25 |   if [ $(uname) == "Linux" ];then
26 |     [ "${lines[3]}" = "|Result: 8 x^4 + 28 x^2" ] ## this works for darwin but the test wont
27 |   fi
28 | }
29 | 
30 | @test "Testing newton bad characters in expression " {
31 |   run newton simplify 3x=
32 |   [ "$status" -eq 1 ]
33 |   [ "${lines[0]}" = "Error: Expression contains invalid characters" ]
34 | }
35 | 
36 | @test "Testing newton bad operation " {
37 |   run newton jokes 2x^2
38 |   [ "$status" -eq 1 ]
39 |   [ "${lines[0]}" = "Error: invalid operation, run newton -h to get a list of valid operations" ]
40 | }
41 | 
42 | @test "Get the tools version with -v" {
43 |   run newton -v
44 |   [ "$status" -eq 0 ]
45 |   result=$( echo $(newton -v) | grep -Eo "Version")
46 |   [ "$result" = "Version" ]
47 | }
48 | 


--------------------------------------------------------------------------------
/tests/qrify.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing qrify tool" {
 4 |    echo qrify
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run qrify update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run qrify -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Qrify" ]
19 | }
20 | 
21 | @test "Getting the qr code for a test string" {
22 |   run qrify this is a test string
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "█████████████████████████████████" ]
25 |   [ "${lines[1]}" = "█████████████████████████████████" ]
26 |   [ "${lines[2]}" = "████ ▄▄▄▄▄ ██▀▄████ ██ ▄▄▄▄▄ ████" ]
27 |   [ "${lines[3]}" = "████ █   █ █▄▀█▄▀█ ▀▀█ █   █ ████" ]
28 |   [ "${lines[4]}" = "████ █▄▄▄█ ██▄▀▀  ▄ ▀█ █▄▄▄█ ████" ]
29 | }
30 | 
31 | 
32 | 
33 | 
34 | 
35 | @test "No arguments prints usage instructions" {
36 |   run qrify
37 |   [ "$status" -eq 0 ]
38 |   [ "${lines[0]}" = "Qrify" ]
39 | }
40 | 
41 | @test "Get the tools version with -v" {
42 |   run qrify -v
43 |   [ "$status" -eq 0 ]
44 |   result=$( echo $(qrify -v) | grep -Eo "Version")
45 |   [ "$result" = "Version" ]
46 | }
47 | 


--------------------------------------------------------------------------------
/tests/short.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | export TOOL_NAME='short'
 4 | 
 5 | setup() {
 6 |   # $REPO_DIR/tests/short.bats
 7 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 8 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 9 | }
10 | 
11 | @test "Testing ${TOOL_NAME} tool" {
12 |   echo "${TOOL_NAME}"
13 | }
14 | 
15 | @test "Confirm the \$REPO_DIR variable is evaluated" {
16 |   cd "${REPO_DIR}" && pwd
17 |   
18 |   [[ "$status" -eq 0 ]]
19 | }
20 | 
21 | # can cd into script dir
22 | @test "Confirm a valid directory for ${TOOL_NAME}" {
23 |   cd "${TOOL_DIR}" && pwd
24 |   
25 |   [[ "$status" -eq 0 ]]
26 | }
27 | 
28 | @test "Check for latest version of bash-snippets on update" {
29 |   if [[ "$(uname)" == "Linux" ]]; then
30 |     run "${TOOL_DIR}/${TOOL_NAME}" update
31 |   
32 |     [[ "$status" -eq 0 ]]
33 |     [ "$output" == "Bash-Snippets is already the latest version" ]
34 |   fi
35 | }
36 | 
37 | @test "The -h option should print usage" {
38 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
39 |   
40 |   [[ "$status" -eq 0 ]]
41 |   # if bash is less than 7 yrs old
42 |   if ((${BASH_VERSINFO[0]} >= 4)); then
43 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
44 |   else
45 |     # or im probably a stoneage mac
46 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
47 |   fi
48 | }
49 | 
50 | @test "No arguments prints usage instructions" {
51 |   run "${TOOL_DIR}/${TOOL_NAME}"
52 |   
53 |   [[ "$status" -eq 0 ]]
54 |   # if bash is less than 7 yrs old
55 |   if ((${BASH_VERSINFO[0]} >= 4)); then
56 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
57 |   else
58 |     # or im probably a stoneage mac
59 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
60 |   fi
61 | }
62 | 
63 | @test "Get the tools version with -v" {
64 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
65 |   
66 |   [[ "$status" -eq 0 ]]
67 |   expected='Version'
68 |   [[ "${output}" =~ "${expected}" ]]
69 | }
70 | 
71 | # Tool specific tests
72 | 
73 | @test "Shorten github repo URL" {
74 |   longurl='https://github.com/alexanderepstein/Bash-Snippets'
75 |   run "${TOOL_DIR}/${TOOL_NAME}" -s "${longurl}"
76 |   
77 |   [[ "$status" -eq 0 ]]
78 |   expected='http://tinyurl.com/.+'
79 |   [[ "${lines[2]}" =~ (${expected}) ]]
80 | }
81 | 
82 | @test "Expand tinyurl URL" {
83 |   shorturl='http://tinyurl.com/uowfbb5'
84 |   run "${TOOL_DIR}/${TOOL_NAME}" -e "${shorturl}"
85 |   
86 |   [[ "$status" -eq 0 ]]
87 |   expected='https://github.com/alexanderepstein/Bash-Snippets'
88 |   [[ "${lines[2]}" =~ "${expected}" ]]
89 | }
90 | 
91 | 


--------------------------------------------------------------------------------
/tests/siteciphers.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing siteciphers tool" {
 4 |    echo siteciphers
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run siteciphers update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "No arguments prints usage instructions" {
16 |   run siteciphers
17 |   [ "$status" -eq 1 ]
18 |   [ "${lines[0]}" = "Siteciphers" ]
19 | }
20 | 
21 | @test "The -h option should print usage" {
22 |   run siteciphers -h
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "Siteciphers" ]
25 | }
26 | 
27 | #@test "Running siteciphers on travis-ci" {
28 | #  run siteciphers travis-ci.org
29 | #  [ "$status" -eq 0 ]
30 | #  [ "${lines[0]}" = "ECDHE-RSA-AES256-GCM-SHA384 - NO (tlsv1 alert insufficient security)" ]
31 | #}
32 | 
33 | 
34 | @test "Get the tools version with -v" {
35 |   run siteciphers -v
36 |   [ "$status" -eq 0 ]
37 |   result=$( echo $(siteciphers -v) | grep -Eo "Version")
38 |   [ "$result" = "Version" ]
39 | }
40 | 


--------------------------------------------------------------------------------
/tests/stocks.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing stocks tool" {
 4 |    echo stocks
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run stocks update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run stocks -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Stocks" ]
19 | }
20 | 
21 | @test "No arguments prints usage instructions" {
22 |   run stocks
23 |   [ "$status" -eq 0 ]
24 |   [ "${lines[0]}" = "Stocks" ]
25 | }
26 | 
27 | @test "Get stock info by passing in ticker" {
28 |   result=$( echo $(stocks AAPL) | grep -Eo "Apple Inc. -- Stock Information" )
29 |   [ "$result" = "Apple Inc. -- Stock Information" ]
30 | 
31 | }
32 | 
33 | @test "Get stock info by passing in company" {
34 |   result=$( echo $(stocks Apple) | grep -Eo "Apple Inc. -- Stock Information" )
35 |   [ "$result" = "Apple Inc. -- Stock Information" ]
36 | }
37 | 
38 | @test "Get the tools version with -v" {
39 |   run stocks -v
40 |   [ "$status" -eq 0 ]
41 |   result=$( echo $(stocks -v) | grep -Eo "Version")
42 |   [ "$result" = "Version" ]
43 | }
44 | 


--------------------------------------------------------------------------------
/tests/taste.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | export TOOL_NAME='taste'
 4 | export TASTE_API_KEY="290044-Taste-QIQUQKOZ"
 5 | 
 6 | setup() {
 7 |   # $REPO_DIR/tests/taste.bats
 8 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 9 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
10 | }
11 | 
12 | @test "Testing ${TOOL_NAME} tool" {
13 |   echo "${TOOL_NAME}"
14 | }
15 | 
16 | @test "Check for latest version of bash-snippets on update" {
17 |   if [[ "$(uname)" == "Linux" ]]; then
18 |     run "${TOOL_DIR}/${TOOL_NAME}" update
19 | 
20 |     [[ "$status" -eq 0 ]]
21 |     [ "$output" == "Bash-Snippets is already the latest version" ]
22 |   fi
23 | }
24 | 
25 | @test "The -h option should print usage" {
26 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
27 | 
28 |   [[ "$status" -eq 0 ]]
29 |   # if bash is less than 7 yrs old
30 |   if ((${BASH_VERSINFO[0]} >= 4)); then
31 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
32 |   else
33 |     # or im probably a stoneage mac
34 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
35 |   fi
36 | }
37 | 
38 | @test "No arguments prints usage instructions" {
39 |   run "${TOOL_DIR}/${TOOL_NAME}"
40 | 
41 |   [[ "$status" -eq 0 ]]
42 |   # if bash is less than 7 yrs old
43 |   if ((${BASH_VERSINFO[0]} >= 4)); then
44 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
45 |   else
46 |     # or im probably a stoneage mac
47 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
48 |   fi
49 | }
50 | 
51 | @test "Get the tools version with -v" {
52 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
53 | 
54 |   [[ "$status" -eq 0 ]]
55 |   expected='Version'
56 |   [[ "${output}" =~ "${expected}" ]]
57 | }
58 | 
59 | @test "Testing short recommendations" {
60 |   run "${TOOL_DIR}/${TOOL_NAME}" 50 Cent
61 | 
62 |   # order of ouput lines changed
63 |   [[ "$status" -eq 0 ]]
64 |   expected='(G-Unit|The Game|Lloyd Banks): .+'
65 |   [ "${lines[0]}" = "===================================" ]
66 |   [[ "${lines[1]}" =~ ${expected} ]]
67 |   [[ "${lines[2]}" =~ ${expected} ]]
68 |   [[ "${lines[3]}" =~ ${expected} ]]
69 |   [ "${lines[4]}" = "===================================" ]
70 | }
71 | 
72 | @test "Testing long recommendations" {
73 |   run "${TOOL_DIR}/${TOOL_NAME}" -i Sublime
74 | 
75 |   [[ "$status" -eq 0 ]]
76 |   expected='Soundsystem is the fifth studio album by 311, released on October 12, 1999. Soundsystem, which was certified Gold by the RIAA,'
77 |   [[ "${output}" =~ "${expected}" ]]
78 | }
79 | 
80 | @test "Testing search on item" {
81 |   run "${TOOL_DIR}/${TOOL_NAME}" -s Kendrick Lamar
82 | 
83 |   [[ "$status" -eq 0 ]]
84 |   expected='Kendrick Lamar Duckworth'
85 |   [[ "${output}" =~ "${expected}" ]]
86 | }
87 | 
88 | 


--------------------------------------------------------------------------------
/tests/todo.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing todo tool" {
 4 |    echo todo
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run todo update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | 
16 | @test "No arguments prints usage instructions" {
17 |   run todo
18 |   [ "$status" -eq 0 ]
19 |   [ "${lines[0]}" = "Todo" ]
20 | }
21 | 
22 | @test "The -h option should print usage" {
23 |   run todo -h
24 |   [ "$status" -eq 0 ]
25 |   [ "${lines[0]}" = "Todo" ]
26 | }
27 | 
28 | @test "Adding task" {
29 |   run todo -a First task ever
30 |   [ "$status" -eq 0 ]
31 |   result=$( echo $(todo -g) | grep -Eo "01\). First task ever" )
32 |   [ "$result" = "01). First task ever" ]
33 | }
34 | 
35 | @test "Getting task" {
36 |   run todo -g
37 |   [ "$status" -eq 0 ]
38 |   result=$( echo $(todo -g) | grep -Eo "01\). First task ever" )
39 |   [ "$result" = "01). First task ever" ]
40 | }
41 | 
42 | @test "Removing task" {
43 |   run todo -r "1"
44 |   [ "$status" -eq 0 ]
45 |   result=$( cat ~/.todo/list.txt )
46 |   echo $result
47 |   [ "$result" = "" ]
48 | }
49 | 
50 | @test "Getting from empty task list" {
51 |   run todo -g
52 |   [ "$status" -eq 0 ]
53 |   [ "$output" = "No tasks found" ]
54 | }
55 | 
56 | @test "Get the tools version with -v" {
57 |   run todo -v
58 |   [ "$status" -eq 0 ]
59 |   result=$( echo $(todo -v) | grep -Eo "Version")
60 |   [ "$result" = "Version" ]
61 | }
62 | 


--------------------------------------------------------------------------------
/tests/transfer.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing transfer tool" {
 4 |    echo transfer
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run transfer update
10 |   [ "$status" -eq 0 ]
11 |   [ "$output" = "Bash-Snippets is already the latest version" ]
12 | fi
13 | }
14 | 
15 | @test "The -h option should print usage" {
16 |   run transfer -h
17 |   [ "$status" -eq 0 ]
18 |   [ "${lines[0]}" = "Transfer" ]
19 | }
20 | 
21 | @test "Testing file upload" {
22 |   touch $HOME/testFile.txt
23 |   echo -n "This is some example content." > $HOME/testFile.txt
24 |   run transfer $HOME/testFile.txt
25 |   transferResponse=$(transfer $HOME/testFile.txt)
26 |   rm -f $HOME/testFile.txt
27 |   transferCommand=$( echo $transferResponse | cut -d 
#39;\n' -f 3 | sed s/"Transfer Download Command:"//g | sed s:"desiredOutputDirectory":"$HOME":g | sed s:"^ "::g)
28 |   transferStatus=$( echo $transferResponse | grep -Eo "Success!")
29 |   [ "$status" -eq 0 ]
30 |   [ "$transferStatus" = "Success!" ] ## this works for darwin but the test wont
31 | }
32 | 
33 | 
34 | #@test "Testing file upload & download" {
35 | #touch $HOME/testFile.txt
36 | #echo -n "This is some example content." > $HOME/testFile.txt
37 | #ransferResponse=$(transfer $HOME/testFile.txt)
38 | #transferCommand=$( echo $transferResponse | cut -d 
#39;\n' -f 3 | sed s/"Transfer Download Command:"//g | sed s:"desiredOutputDirectory":"$HOME":g | sed s:"^ "::g)
39 | #id=$(echo $transferResponse | cut -d "/" -f 4)
40 | #transferStatus=$( echo $transferResponse | grep -Eo "Success!")
41 | #[ "$transferStatus" = "Success!" ]
42 | #rm -f $HOME/testFile.txt
43 | #if [ -f  $HOME/testFile.txt ];then exit 1;fi
44 | #run transfer -d $HOME $id testFile.txt
45 | #if [ ! -f  $HOME/testFile.txt ];then exit 1;fi
46 | #contents=$(cat $HOME/testFile.txt)
47 | #if [ $contents != "This is some example content." ];then exit 1; fi
48 | #rm -f $HOME/testFile.txt
49 | #transferResponse=$(transfer -d $HOME $id testFile.txt)
50 | #transferStatus=$( echo $transferResponse | grep -Eo "Success!")
51 | #[ "$transferStatus" = "Success!" ]
52 | #rm -f $HOME/testFile.txt
53 | #}
54 | 
55 | @test "Get the tools version with -v" {
56 |   run transfer -v
57 |   [ "$status" -eq 0 ]
58 |   result=$( echo $(transfer -v) | grep -Eo "Version")
59 |   [ "$result" = "Version" ]
60 | }
61 | 


--------------------------------------------------------------------------------
/tests/weather.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | export TOOL_NAME='weather'
 4 | 
 5 | setup() {
 6 |   # $REPO_DIR/tests/weather.bats
 7 |   REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)"
 8 |   TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)"
 9 | }
10 | 
11 | @test "Testing ${TOOL_NAME} tool" {
12 |   echo "${TOOL_NAME}"
13 | }
14 | 
15 | @test "Confirm the \$REPO_DIR variable is evaluated" {
16 |   cd "${REPO_DIR}" && pwd
17 | 
18 |   [[ "$status" -eq 0 ]]
19 | }
20 | 
21 | # can cd into script dir
22 | @test "Confirm a valid directory for ${TOOL_NAME}" {
23 |   cd "${TOOL_DIR}" && pwd
24 | 
25 |   [[ "$status" -eq 0 ]]
26 | }
27 | 
28 | @test "Check for latest version of bash-snippets on update" {
29 |   if [[ "$(uname)" == "Linux" ]]; then
30 |     run "${TOOL_DIR}/${TOOL_NAME}" update
31 | 
32 |     [[ "$status" -eq 0 ]]
33 |     [ "$output" == "Bash-Snippets is already the latest version" ]
34 |   fi
35 | }
36 | 
37 | @test "The -h option should print usage" {
38 |   run "${TOOL_DIR}/${TOOL_NAME}" -h
39 | 
40 |   [[ "$status" -eq 0 ]]
41 |   # if bash is less than 7 yrs old
42 |   if ((${BASH_VERSINFO[0]} >= 4)); then
43 |     [[ "${lines[0]}" = "${TOOL_NAME^}" ]]
44 |   else
45 |     # or im probably a stoneage mac
46 |     [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]]
47 |   fi
48 | }
49 | 
50 | @test "No arguments shows weather at current location" {
51 |   run "${TOOL_DIR}/${TOOL_NAME}"
52 | 
53 |   [[ "$status" -eq 0 ]]
54 |   expected='Weather report: .+'
55 |   [[ "${lines[0]}" =~ ${expected} ]]
56 | }
57 | 
58 | @test "Get the tools version with -v" {
59 |   run "${TOOL_DIR}/${TOOL_NAME}" -v
60 | 
61 |   [[ "$status" -eq 0 ]]
62 |   expected='Version'
63 |   [[ "${output}" =~ "${expected}" ]]
64 | }
65 | 
66 | # Tool specific tests
67 | @test "Testing weather with specified location" {
68 |   run "${TOOL_DIR}/${TOOL_NAME}" Paramus
69 | 
70 |   [ "$status" -eq 0 ]
71 |   # API changed
72 |   #[ "${lines[0]}" = "Weather report: Paramus, United States of America" ]
73 |   [ "${lines[0]}" = "Weather report: Paramus" ]
74 | }
75 | 
76 | 


--------------------------------------------------------------------------------
/tests/ytview.bats:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bats
 2 | 
 3 | @test "Testing ytview tool" {
 4 |    echo ytview
 5 | }
 6 | 
 7 | @test "Check for latest version of bash-snippets on update" {
 8 |   if [[ "$(uname)" == "Linux" ]];then
 9 |   run ytview update
10 |   [ "$output" = "Bash-Snippets is already the latest version" ]
11 | fi
12 | }
13 | 
14 | @test "The -h option should print usage" {
15 |   run ytview -h
16 |   [ "${lines[0]}" = "Ytview" ]
17 | }
18 | 
19 | @test "No arguments prints usage instructions" {
20 |   run ytview
21 |   [ "$status" -eq 0 ]
22 |   [ "${lines[0]}" = "Ytview" ]
23 | }
24 | 
25 | @test "Get the tools version with -v" {
26 |   result=$( echo $(ytview -v) | grep -Eo "Version")
27 |   [ "$result" = "Version" ]
28 | }
29 | 


--------------------------------------------------------------------------------
/todo/todo:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | flag=""
  4 | currentVersion="1.23.0"
  5 | configuredClient=""
  6 | 
  7 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
  8 | getConfiguredClient()
  9 | {
 10 |   if  command -v curl &>/dev/null; then
 11 |     configuredClient="curl"
 12 |   elif command -v wget &>/dev/null; then
 13 |     configuredClient="wget"
 14 |   elif command -v http &>/dev/null; then
 15 |     configuredClient="httpie"
 16 |   elif command -v fetch &>/dev/null; then
 17 |     configuredClient="fetch"
 18 |   else
 19 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 20 |     return 1
 21 |   fi
 22 | }
 23 | 
 24 | ## Allows to call the users configured client without if statements everywhere
 25 | httpGet()
 26 | {
 27 |   case "$configuredClient" in
 28 |     curl)  curl -A curl -s "$@" ;;
 29 |     wget)  wget -qO- "$@" ;;
 30 |     httpie) http -b GET "$@" ;;
 31 |     fetch) fetch -q "$@" ;;
 32 |   esac
 33 | }
 34 | 
 35 | update()
 36 | {
 37 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 38 |   # Update utility version 2.2.0
 39 |   # To test the tool enter in the defualt values that are in the examples for each variable
 40 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 41 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 42 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 43 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 44 | 
 45 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 46 |     echo "Error: update utility has not been configured correctly." >&2
 47 |     exit 1
 48 |   elif [[ $latestVersion == "" ]]; then
 49 |     echo "Error: no active internet connection" >&2
 50 |     exit 1
 51 |   else
 52 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 53 |       echo "Version $latestVersion available"
 54 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 55 |       read -r answer
 56 |       if [[ "$answer" == [Yy] ]]; then
 57 |         cd ~ || { echo 'Update Failed'; exit 1; }
 58 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 59 |         echo -n "Downloading latest version of: $repositoryName."
 60 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 61 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 62 |         rm -f .BSnippetsHiddenFile
 63 |         echo "Success!"
 64 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 65 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 66 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 67 |         ./$nameOfInstallFile "update" || exit 1
 68 |         cd ..
 69 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 70 |       else
 71 |         exit 1
 72 |       fi
 73 |     else
 74 |       echo "$repositoryName is already the latest version"
 75 |     fi
 76 |   fi
 77 | }
 78 | 
 79 | addTask()
 80 | {
 81 |   if [ ! -f ~/.todo/list.txt ]; then
 82 |     if [ ! -d ~/.todo ]; then mkdir ~/.todo; fi
 83 |     touch ~/.todo/list.txt
 84 |   fi
 85 |   echo "$1       ;      $(date)" >> ~/.todo/list.txt
 86 | }
 87 | 
 88 | checkInternet()
 89 | {
 90 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 91 | }
 92 | 
 93 | removeTask()
 94 | {
 95 |   ## Check for valid task numbers (valid characters)
 96 |   if [ -f ~/.todo/temp.txt ];then rm -f ~/.todo/temp.txt;fi
 97 |   touch ~/.todo/temp.txt
 98 |   for taskToRemove in "$@";do
 99 |     oldTaskNumber=$taskToRemove
100 |     taskNumber=$( echo "$taskToRemove" | grep -Eo "[0-9]*" )
101 |     if [[ $taskNumber == "" || $oldTaskNumber != $taskNumber ]]; then echo "Error: $oldTaskNumber is not a valid task number!" && return 1; fi
102 |   done
103 |   count="0"
104 |   IFS=
#39;\n'       # make newlines the only separator
105 | 
106 |   ## Removing the task (only don't add to temp if we should remove it)
107 |   for task in $(cat ~/.todo/list.txt); do
108 |     removeIt="false"
109 |     for taskToRemove in "$@";do
110 |       if [[ $(($count + 1)) == "$taskToRemove" ]]; then
111 |       removeIt="true"
112 |       break
113 |       fi
114 |     done
115 |     if ! $removeIt ;then echo "$task" >> ~/.todo/temp.txt;fi
116 |     count=$(( $count + 1 ))
117 |   done
118 |   rm -f ~/.todo/list.txt
119 |   cp  ~/.todo/temp.txt ~/.todo/list.txt
120 |   rm -f ~/.todo/temp.txt
121 | 
122 |   ##Checking if the task exists
123 |   for taskToRemove in "$@" ;do
124 |     if [ $count -lt "$taskToRemove" ]; then
125 |       echo "Error: task number $taskToRemove does not exist!"
126 |     else
127 |       echo "Sucessfully removed task number $taskToRemove"
128 |     fi
129 |   done
130 | }
131 | 
132 | getTasks()
133 | {
134 |   if [ -f ~/.todo/list.txt ]; then
135 |     checkEmpty=$(cat ~/.todo/list.txt)
136 |     if [[ $checkEmpty == "" ]]; then
137 |       echo "No tasks found"
138 |     else
139 |       count="1"
140 |       IFS=
#39;\n'       # make newlines the only separator
141 |       for task in $(cat ~/.todo/list.txt); do
142 |         tempTask=$count
143 |         if [ $count -lt 10 ]; then tempTask="0$count"; fi
144 |         echo "$tempTask). $task"  >> ~/.todo/getTemp.txt
145 |         count=$(( $count + 1 ))
146 |       done
147 |       cat ~/.todo/getTemp.txt | column -t -s ";"
148 |       rm -f ~/.todo/getTemp.txt
149 |     fi
150 |   else
151 |     echo "No tasks found"
152 |   fi
153 | }
154 | 
155 | usage()
156 | {
157 |   cat <<EOF
158 | Todo
159 | Description: A simplistic commandline todo list.
160 | Usage: todo [flags] or todo [flags] [arguments]
161 |   -c  Clear all the current tasks
162 |       Can also use clear instead of -c
163 |   -r  Remove the following task numbers seprated by spaces
164 |       Can also use remove instead of -r
165 |   -g  Get the current tasks
166 |       Can also use list instead of -g
167 |   -a  Add the following task
168 |       Can also use add instead of -a
169 |   -u  Update Bash-Snippet Tools
170 |   -h  Show the help
171 |   -v  Get the tool version
172 | Examples:
173 |    todo -a My very first task
174 |    todo remove 2
175 |    todo -r 1 3
176 |    todo add Another Task
177 |    todo list
178 |    todo -g
179 |    todo -c
180 |    todo clear
181 | EOF
182 | }
183 | 
184 | clearAllTasks()
185 | {
186 |   rm -f ~/.todo/list.txt || return 1
187 |   touch ~/.todo/list.txt || return 1
188 |   echo "Tasks cleared."
189 | }
190 | 
191 | while getopts "cr:a:guvh" opt; do
192 |   case "$opt" in
193 |     \?) echo "Invalid option: -$OPTARG" >&2
194 |         exit 1
195 |         ;;
196 |     c)  if [[ $flag == "" ]]; then
197 |           flag="clear"
198 |         else
199 |           echo "Error: all flags are mutually exclusive"
200 |           exit 1
201 |         fi
202 |         ;;
203 |     h)  usage
204 |         exit 0
205 |         ;;
206 |     v)  echo "Version $currentVersion"
207 |         exit 0
208 |         ;;
209 |     g)  if [[ $flag == "" ]]; then
210 |           flag="get"
211 |         else
212 |           echo "Error: all flags are mutually exclusive"
213 |           exit 1
214 |         fi
215 |         ;;
216 |     r)  if [[ $flag == "" ]]; then
217 |           flag="remove"
218 |         else
219 |           echo "Error: all flags are mutually exclusive"
220 |           exit 1
221 |         fi
222 |         ;;
223 |     a)  if [[ $flag == "" ]]; then
224 |           flag="add"
225 |         else
226 |           echo "Error: all flags are mutually exclusive"
227 |           exit 1
228 |         fi
229 |         ;;
230 |     u)  getConfiguredClient || exit 1
231 |         checkInternet || exit 1
232 |         update
233 |         exit 0
234 |         ;;
235 |     :)  echo "Option -$OPTARG requires an argument." >&2
236 |         exit 1
237 |         ;;
238 |   esac
239 | done
240 | 
241 | if [[ $# == "0" ]]; then
242 |   usage
243 | elif [[ $# == "1" ]]; then
244 |   if [[ $1 == "clear" ]]; then
245 |     clearAllTasks || exit 1
246 |   elif [[ $1 == "update" ]]; then
247 |     getConfiguredClient || exit 1
248 |     checkInternet || exit 1
249 |     update || exit 1
250 |     exit 0
251 |   elif [[ $1 == "help" ]]; then
252 |     usage
253 |     exit 0
254 |   elif [[ $flag == "clear" || $1 == "clear" ]]; then clearAllTasks || exit 1
255 |   elif [[ $flag == "get" || $1 == "list" || $1 == "get" ]]; then getTasks || exit 1
256 |   else { echo "Error: the argument $1 is not valid"; exit 1; }; fi
257 | else
258 |   if [[ $flag == "add" || $1 == "add" ]]; then addTask "${*:2}" && getTasks || exit 1
259 |   elif [[ $flag == "remove" || $1 == "remove" ]]; then removeTask "${*:2}" && getTasks || exit 1
260 |   else { usage; exit 1; }; fi
261 | fi
262 | 


--------------------------------------------------------------------------------
/todo/todo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/todo/todo.png


--------------------------------------------------------------------------------
/transfer/transfer:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | configuredDownloadClient=""
  4 | configuredUploadClient=""
  5 | configuredClient=""
  6 | currentVersion="1.23.0"
  7 | down="false"
  8 | 
  9 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 10 | getConfiguredDownloadClient()
 11 | {
 12 |   if  command -v curl &>/dev/null; then
 13 |     configuredDownloadClient="curl"
 14 |   elif command -v wget &>/dev/null; then
 15 |     configuredDownloadClient="wget"
 16 |   elif command -v fetch &>/dev/null; then
 17 |     configuredDownloadClient="fetch"
 18 |   else
 19 |     echo "Error: Downloading with this tool requires either curl, wget, or fetch to be installed." >&2
 20 |     return 1
 21 |   fi
 22 | }
 23 | 
 24 | ## Allows to call the users configured client without if statements everywhere
 25 | httpGet()
 26 | {
 27 |   case "$configuredClient" in
 28 |     curl)  curl -A curl -s "$@" ;;
 29 |     wget)  wget -qO- "$@" ;;
 30 |     httpie) http -b GET "$@" ;;
 31 |     fetch) fetch -q "$@" ;;
 32 |   esac
 33 | }
 34 | 
 35 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 36 | getConfiguredClient()
 37 | {
 38 |   if  command -v curl &>/dev/null; then
 39 |     configuredClient="curl"
 40 |   elif command -v wget &>/dev/null; then
 41 |     configuredClient="wget"
 42 |   elif command -v http &>/dev/null; then
 43 |     configuredClient="httpie"
 44 |   elif command -v fetch &>/dev/null; then
 45 |     configuredClient="fetch"
 46 |   else
 47 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2
 48 |     return 1
 49 |   fi
 50 | }
 51 | 
 52 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 53 | getconfiguredUploadClient()
 54 | {
 55 |   if  command -v curl &>/dev/null; then
 56 |     configuredUploadClient="curl"
 57 |   elif command -v wget &>/dev/null; then
 58 |     configuredUploadClient="wget"
 59 |   else
 60 |     echo "Error: Uploading with this tool requires either curl or wget to be installed." >&2
 61 |     return 1
 62 |   fi
 63 | }
 64 | 
 65 | update()
 66 | {
 67 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 68 |   # Update utility version 2.2.0
 69 |   # To test the tool enter in the defualt values that are in the examples for each variable
 70 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 71 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 72 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 73 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 74 | 
 75 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 76 |     echo "Error: update utility has not been configured correctly." >&2
 77 |     exit 1
 78 |   elif [[ $latestVersion == "" ]]; then
 79 |     echo "Error: no active internet connection" >&2
 80 |     exit 1
 81 |   else
 82 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 83 |       echo "Version $latestVersion available"
 84 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 85 |       read -r answer
 86 |       if [[ "$answer" == [Yy] ]]; then
 87 |         cd ~ || { echo 'Update Failed'; exit 1; }
 88 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 89 |         echo -n "Downloading latest version of: $repositoryName."
 90 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 91 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 92 |         rm -f .BSnippetsHiddenFile
 93 |         echo "Success!"
 94 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 95 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 96 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 97 |         ./$nameOfInstallFile "update" || exit 1
 98 |         cd ..
 99 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
100 |       else
101 |         exit 1
102 |       fi
103 |     else
104 |       echo "$repositoryName is already the latest version"
105 |     fi
106 |   fi
107 | }
108 | 
109 | checkInternet()
110 | {
111 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
112 | }
113 | 
114 | singleUpload()
115 | {
116 |   filePath=$(echo "$1" | sed s:"~":"$HOME":g)
117 |   if [ ! -f "$filePath" ];then { echo "Error: invalid file path"; return 1;}; fi
118 |   tempFileName=$(echo "$1" | sed "s/.*\///")
119 |   echo "Uploading $tempFileName"
120 |   httpSingleUpload "$filePath" "$tempFileName"
121 | }
122 | 
123 | 
124 | httpSingleUpload()
125 | {
126 |   case "$configuredUploadClient" in
127 |     curl) response=$( curl --progress-bar --upload-file $1 "https://free.keep.sh" | tee /dev/null) || { echo "Failure!"; return 1;};;
128 |     wget) response=$(wget --progress=dot --method PUT --body-file="$1" "https://free.keep.sh" | tee /dev/null) || { echo "Failure!"; return 1;} ;;
129 |   esac
130 |   echo  "Success!"
131 | }
132 | 
133 | printUploadResponse()
134 | {
135 | fileID=$(echo "$response" | cut -d "/" -f 4)
136 |   echo "Transfer Download Command: transfer -d desiredOutputDirectory $fileID $tempFileName"
137 |   echo "Transfer File URL: $response"
138 |   echo -e "\n\n\t Or scan this QR Code"
139 |   qrify $response
140 | }
141 | 
142 | 
143 | onetimeUpload()
144 | {
145 | 	getConfiguredClient
146 |     checkInternet || exit 0
147 |     getconfiguredUploadClient
148 |   	response=$(curl --progress-bar -T $1 temp.sh)
149 |   	downlink=$(echo "$response")
150 | }
151 | 
152 | 
153 | printOnetimeUpload()
154 | {
155 |   	echo -e "\n Download link: $downlink"
156 |   	echo -e "\n\n\t Or scan this QR Code"
157 |   	qrify $downlink
158 | }
159 | 
160 | singleDownload()
161 | {
162 |   if [[ ! -d $1 ]];then 
163 |   	{
164 |   		echo "Directory doesn't exist, creating it now...";
165 |   		mkdir -p "$1";
166 |   	};
167 |   fi
168 | 
169 |   tempOutputPath=$1
170 |   if [ -f "$tempOutputPath/$3" ];then
171 |   	echo -n "File aleady exists at $tempOutputPath/$3, do you want to delete it? [Y/n] ";
172 |   	read -r answer
173 |     if [[ "$answer" == [Yy] ]] ;then
174 |     	rm -rf "$tempOutputPath"/"$3";
175 |     	else
176 |     		echo "Stopping download"
177 |     		return 1;
178 |     fi
179 |   fi
180 |   echo "Downloading $3"
181 |   curl -# -L https://free.keep.sh/$2/$3 > $1/$3 || { echo "Failure"; return 1;}
182 |   # curl -# -L https://temp.sh/$2/$3 > $1/$3 || { echo "Failure"; return 1;}
183 |   echo "Success!"
184 | }
185 | 
186 | usage()
187 | {
188 |   cat <<EOF
189 | Transfer
190 | Description: Quickly transfer files from the command line.
191 | Usage: transfer [flags] or transfer [flag] [args] or transfer [filePathToUpload]
192 |   -d  Download a single file
193 |       First arg: Output file directory
194 |       Second arg: File url id
195 |       Third arg: File name
196 |   -o  Onetime file upload
197 |   -u  Update Bash-Snippet Tools
198 |   -h  Show the help
199 |   -v  Get the tool version
200 | Examples:
201 |   transfer ~/fileToTransfer.txt
202 |   transfer ~/firstFileToTransfer.txt ~/secondFileToTransfer.txt ~/thirdFileToTransfer.txt
203 |   transfer -d ~/outputDirectory fileID fileName
204 |   transfer -o ~/fileToTransfer.txt
205 | EOF
206 | }
207 | 
208 | while getopts "o:d:uvh" opt; do
209 |   case "$opt" in
210 |     \?) echo "Invalid option: -$OPTARG" >&2
211 |       exit 1
212 |     ;;
213 |     h)  usage
214 |       exit 0
215 |     ;;
216 |     v)  echo "Version $currentVersion"
217 |       exit 0
218 |     ;;
219 |     u)
220 |       getConfiguredClient || exit 1
221 |       checkInternet || exit 1
222 |       update || exit 1
223 |       exit 0
224 |     ;;
225 |     o)
226 |       onetime="true"
227 |     ;;
228 |     d)
229 |       down="true"
230 |       if [ $# -lt 4 ];
231 |       	then
232 |       		echo "Error: not enough arguments for downloading a file, see the usage"; exit 1
233 |       fi
234 |       
235 |       if [ $# -gt 4 ];
236 |       	then
237 |       		echo "Error: to many enough arguments for downloading a file, see the usage"; exit 1
238 |       	fi
239 |       inputFilePath=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 2)
240 |       inputID=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 3)
241 |       inputFileName=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 4)
242 |     ;;
243 |     :)  echo "Option -$OPTARG requires an argument." >&2
244 |       exit 1
245 |     ;;
246 |   esac
247 | done
248 | 
249 | if [[ $# == "0" ]]; then
250 |   usage
251 |   exit 0
252 | elif [[ $# == "1" ]];then
253 |   if [[ $1 == "help" ]]; then
254 |     usage
255 |     exit 0
256 |   elif [[ $1 == "update" ]]; then
257 |     getConfiguredClient || exit 1
258 |     checkInternet || exit 1
259 |     update || exit 1
260 |     exit 0
261 |   elif [ -f "$1" ];then
262 |     getConfiguredClient || exit 1
263 |     checkInternet || exit 1
264 |     getconfiguredUploadClient || exit 1
265 |     singleUpload "$1" || exit 1
266 |     printUploadResponse
267 |     exit 0
268 |   else
269 |     echo "Error: invalid filepath"
270 |     exit 1
271 |   fi
272 | else
273 |   if $down ;then
274 |     getConfiguredClient || exit 1
275 |     checkInternet || exit 1
276 |     getConfiguredDownloadClient || exit 1
277 |     singleDownload "$inputFilePath" "$inputID" "$inputFileName" || exit 1
278 |     exit 0
279 |   elif ! $down && ! $onetime; then
280 |     getConfiguredClient || exit 1
281 |     checkInternet || exit 1
282 |     getconfiguredUploadClient || exit 1
283 |     for path in "$@";do
284 |       singleUpload "$path" || exit 1
285 |       printUploadResponse
286 |       echo
287 |     done
288 |     exit 0
289 |   elif ! $down && $onetime; then
290 |     getConfiguredClient || exit 1
291 |     if [[ $configuredClient -ne "curl" ]];then
292 |       echo "Error: curl must be installed to use one time file upload"
293 |       exit 1
294 |     fi
295 |     inputFileName=$(echo "$*" | sed s/-o//g | cut -d " " -f 2 )
296 |     onetimeUpload "$inputFileName"
297 |     printOnetimeUpload
298 |   fi
299 | fi
300 | 


--------------------------------------------------------------------------------
/transfer/transfer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/transfer/transfer.png


--------------------------------------------------------------------------------
/uninstall.sh:
--------------------------------------------------------------------------------
 1 | #!/usr/bin/env bash
 2 | # Author: Alexander Epstein https://github.com/alexanderepstein
 3 | declare -a tools=(bak2dvd bash-snippets cheat cloudup crypt cryptocurrency currency geo gist lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview)
 4 | all="1"
 5 | 
 6 | askUninstall()
 7 | {
 8 |   if [[ -f /usr/local/bin/$1 ]]; then
 9 |     echo -n "Do you wish to uninstall $1 [Y/n]: "
10 |     read -r answer
11 |     if [[ "$answer" == [Yy] ]]; then
12 |       echo -n "Removing $1: "
13 |       rm -f /usr/local/bin/"$1" > /dev/null 2>&1 || { echo "Failed" ; echo "Error removing file, try running uninstall script as sudo"; exit 1; }
14 |       echo "Success"
15 |     else
16 |       all="0"
17 |     fi
18 |     unset answer
19 |   fi
20 | }
21 | 
22 | removeTool()
23 | {
24 |   if [[ -f /usr/local/bin/$1 ]]; then
25 |     echo -n "Removing $1: "
26 |     rm -f /usr/local/bin/"$1" > /dev/null 2>&1 || { echo "Failed" ; echo "Error removing file, try running uninstall script as sudo"; exit 1; }
27 |     echo "Success"
28 |   fi
29 | }
30 | 
31 | removeManpage()
32 | {
33 |   if [ -f "/usr/local/man/man1/bash-snippets.1" ]; then rm -f "usr/local/man/man1/bash-snippets.1" || { echo "Error removing manpage, try running uninstall script as sudo"; exit 1; } ; fi
34 |   if [ -f "/usr/local/share/man/man1/bash-snippets.1" ]; then rm -f "/usr/local/share/man/man1/bash-snippets.1" || { echo "Error removing manpage, try running uninstall script as sudo"; exit 1; } ; fi
35 | }
36 | 
37 | if [[ $1 != "all" ]]; then
38 |   for tool in "${tools[@]}"; do
39 |     askUninstall "$tool" || exit 1
40 |   done
41 | else
42 |   for tool in "${tools[@]}"; do
43 |     removeTool "$tool" || exit 1
44 |   done
45 | fi
46 | 
47 | if [[ $all == "1" ]]; then
48 |   removeManpage || exit 1
49 | fi
50 | 


--------------------------------------------------------------------------------
/weather/moon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/weather/moon.png


--------------------------------------------------------------------------------
/weather/weather:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Alexander Epstein https://github.com/alexanderepstein
  3 | 
  4 | currentVersion="1.23.0" #This version variable should not have a v but should contain all other characters ex Github release tag is v1.2.4 currentVersion is 1.2.4
  5 | LANG="${LANG:-en}"
  6 | locale=$(echo "$LANG" | cut -c1-2)
  7 | unset configuredClient
  8 | if [[ $(echo "$locale" | grep -Eo "[a-z A-Z]*" | wc -c) != 3 ]]; then locale="en"; fi
  9 | 
 10 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 11 | getConfiguredClient()
 12 | {
 13 |   if command -v curl &>/dev/null; then
 14 |     configuredClient="curl"
 15 |   elif command -v wget &>/dev/null; then
 16 |     configuredClient="wget"
 17 |   elif command -v http &>/dev/null; then
 18 |     configuredClient="httpie"
 19 |   elif command -v fetch &>/dev/null; then
 20 |     configuredClient="fetch"
 21 |   else
 22 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed\." >&2
 23 |     return 1
 24 |   fi
 25 | }
 26 | 
 27 | ## Allows to call the users configured client without if statements everywhere
 28 | httpGet()
 29 | {
 30 |   case "$configuredClient" in
 31 |     curl)  curl -A curl -s "$@" ;;
 32 |     wget)  wget -qO- "$@" ;;
 33 |     httpie) http -b GET "$@" ;;
 34 |     fetch) fetch -q "$@" ;;
 35 |   esac
 36 | }
 37 | 
 38 | getIPWeather()
 39 | {
 40 |   country=$(httpGet ipinfo.io/country) > /dev/null ## grab the country
 41 |   if [[ $country == "US" ]]; then ## if were in the us id rather not use longitude and latitude so the output is nicer
 42 |     city=$(httpGet ipinfo.io/city) > /dev/null
 43 |     region=$(httpGet ipinfo.io/region) > /dev/null
 44 |     if [[ $(echo "$region" | wc -w) == 2 ]];then
 45 |       region=$(echo "$region" | grep -Eo "[A-Z]*" | tr -d "[:space:]")
 46 |     fi
 47 |     httpGet $locale.wttr.in/"$city","$region""$1"
 48 |   else ## otherwise we are going to use longitude and latitude
 49 |     location=$(httpGet ipinfo.io/loc) > /dev/null
 50 |     httpGet $locale.wttr.in/"$location""$1"
 51 |   fi
 52 | }
 53 | 
 54 | getLocationWeather()
 55 | {
 56 |   args=$(echo "$@" | tr " " + )
 57 |   httpGet $locale.wttr.in/"${args}"
 58 | }
 59 | 
 60 | checkInternet()
 61 | {
 62 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 63 | }
 64 | 
 65 | update()
 66 | {
 67 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 68 |   # Update utility version 2.2.0
 69 |   # To test the tool enter in the defualt values that are in the examples for each variable
 70 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 71 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 72 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 73 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 74 | 
 75 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 76 |     echo "Error: update utility has not been configured correctly." >&2
 77 |     exit 1
 78 |   elif [[ $latestVersion == "" ]]; then
 79 |     echo "Error: no active internet connection" >&2
 80 |     exit 1
 81 |   else
 82 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 83 |       echo "Version $latestVersion available"
 84 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 85 |       read -r answer
 86 |       if [[ "$answer" == [Yy] ]]; then
 87 |         cd ~ || { echo 'Update Failed'; exit 1; }
 88 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 89 |         echo -n "Downloading latest version of: $repositoryName."
 90 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 91 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 92 |         rm -f .BSnippetsHiddenFile
 93 |         echo "Success!"
 94 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 95 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 96 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 97 |         ./$nameOfInstallFile "update" || exit 1
 98 |         cd ..
 99 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
100 |       else
101 |         exit 1
102 |       fi
103 |     else
104 |       echo "$repositoryName is already the latest version"
105 |     fi
106 |   fi
107 | }
108 | 
109 | usage()
110 | {
111 |   cat <<EOF
112 | Weather
113 | Description: Provides a 3 day forecast on your current location or a specified location.
114 |   With no flags Weather will default to your current location.
115 | Usage: weather or weather [flag] or weather [country] or weather [city] [state]
116 |   weather [i][M] get weather in imperial units, optional M means windspeed in m/s
117 |   weather [m][M] get weather in metric units, optional M means windspeed in m/s
118 |   weather [Moon] grabs the phase of the moon
119 |   -u  Update Bash-Snippet Tools
120 |   -h  Show the help
121 |   -v  Get the tool version
122 | Examples:
123 |   weather
124 |   weather Paris m
125 |   weather Tokyo
126 |   weather Moon
127 |   weather mM
128 | EOF
129 | }
130 | 
131 | getConfiguredClient || exit 1
132 | 
133 | while getopts "uvh" opt; do
134 |   case "$opt" in
135 |     \?) echo "Invalid option: -$OPTARG" >&2
136 |         exit 1
137 |         ;;
138 |     h)  usage
139 |         exit 0
140 |         ;;
141 |     v)  echo "Version $currentVersion"
142 |         exit 0
143 |         ;;
144 |     u)  checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here
145 |         update || exit 1
146 |         exit 0
147 |         ;;
148 |     :)  echo "Option -$OPTARG requires an argument." >&2
149 |         exit 1
150 |         ;;
151 |   esac
152 | done
153 | 
154 | if [[ $# == "0" ]]; then
155 |   checkInternet || exit 1
156 |   getIPWeather || exit 1
157 |   exit 0
158 | elif [[ $1 == "help" || $1 == ":help" ]]; then
159 |   usage
160 |   exit 0
161 | elif [[ $1 == "update" ]]; then
162 |   checkInternet || exit 1
163 |   update || exit 1
164 |   exit 0
165 | fi
166 | 
167 | checkInternet || exit 1
168 | if [[ $1 == "m" ]]; then
169 |   getIPWeather "?m" || exit 1
170 | elif [[ "${@: -1}" == "m" ]];then
171 |   args=$( echo "${@:1:(($# - 1))}" ?m | sed s/" "//g)
172 |   getLocationWeather "$args" || exit 1
173 | elif [[ $1 == "M" ]]; then
174 |   getIPWeather "?M" || exit 1
175 | elif [[ "${@: -1}" == "M" ]];then
176 |   args=$( echo "${@:1:(($# - 1))}" ?M | sed s/" "//g)
177 |   getLocationWeather "$args" || exit 1
178 | elif [[ $1 == "mM" || $1 == "Mm" ]]; then
179 |   getIPWeather "?m?M" || exit 1
180 | elif [[ "${@: -1}" == "mM" || "${@:-1}" == "Mm" ]];then
181 |   args=$( echo "${@:1:(($# - 1))}" ?m?M | sed s/" "//g)
182 |   getLocationWeather "$args" || exit 1
183 | elif [[ $1 == "iM" || $1 == "Mi" ]]; then
184 |   getIPWeather "?u?M" || exit 1
185 | elif [[ "${@: -1}" == "iM" || "${@:-1}" == "Mi" ]];then
186 |   args=$( echo "${@:1:(($# - 1))}" ?u?M | sed s/" "//g)
187 |   getLocationWeather "$args" || exit 1
188 | elif [[ $1 == "i" ]]; then
189 |   getIPWeather "?u" || exit 1
190 | elif [[ "${@: -1}" == "i" ]];then
191 |   args=$( echo "${@:1:(($# - 1))}" ?u | sed s/" "//g)
192 |   getLocationWeather "$args" || exit 1
193 | else
194 |   getLocationWeather "$@" || exit 1
195 | fi
196 | 


--------------------------------------------------------------------------------
/weather/weather.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/weather/weather.png


--------------------------------------------------------------------------------
/ytview/ytview:
--------------------------------------------------------------------------------
  1 | #!/usr/bin/env bash
  2 | # Author: Linyos Torovoltos https://github.com/linyostorovovoltos
  3 | # Modifications: Alexander Epstein https://github.com/alexanderepstein
  4 | 
  5 | if [[ -d $HOME/.cache/ytview ]]; then rm -rf "$HOME"/.cache/ytview/; fi
  6 | 
  7 | player=""
  8 | configuredClient=""
  9 | currentVersion="1.23.0"
 10 | flag=""
 11 | 
 12 | ## This function determines which http get tool the system has installed and returns an error if there isnt one
 13 | getConfiguredClient()
 14 | {
 15 |   if  command -v curl &>/dev/null; then
 16 |     configuredClient="curl"
 17 |   elif command -v wget &>/dev/null; then
 18 |     configuredClient="wget"
 19 |   elif command -v http &>/dev/null; then
 20 |     configuredClient="httpie"
 21 |   elif command -v fetch &>/dev/null; then
 22 |     configuredClient="fetch"
 23 |   else
 24 |     echo "Error: This tool requires either curl, wget, httpie or fetch to be installed\." >&2
 25 |     return 1
 26 |   fi
 27 | }
 28 | 
 29 | ## Allows to call the users configured client without if statements everywhere
 30 | httpGet()
 31 | {
 32 |   case "$configuredClient" in
 33 |     curl)  curl -A curl -s "$@" ;;
 34 |     wget)  wget -qO- "$@" ;;
 35 |     httpie) http -b GET "$@" ;;
 36 |     fetch) fetch -q "$@" ;;
 37 |   esac
 38 | }
 39 | 
 40 | checkInternet()
 41 | {
 42 |   httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request
 43 | }
 44 | 
 45 | update()
 46 | {
 47 |   # Author: Alexander Epstein https://github.com/alexanderepstein
 48 |   # Update utility version 2.2.0
 49 |   # To test the tool enter in the defualt values that are in the examples for each variable
 50 |   repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite
 51 |   githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein
 52 |   nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one
 53 |   latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option
 54 | 
 55 |   if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then
 56 |     echo "Error: update utility has not been configured correctly." >&2
 57 |     exit 1
 58 |   elif [[ $latestVersion == "" ]]; then
 59 |     echo "Error: no active internet connection" >&2
 60 |     exit 1
 61 |   else
 62 |     if [[ "$latestVersion" != "$currentVersion" ]]; then
 63 |       echo "Version $latestVersion available"
 64 |       echo -n "Do you wish to update $repositoryName [Y/n]: "
 65 |       read -r answer
 66 |       if [[ "$answer" == [Yy] ]]; then
 67 |         cd ~ || { echo 'Update Failed'; exit 1; }
 68 |         if [[ -d  ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi
 69 |         echo -n "Downloading latest version of: $repositoryName."
 70 |         git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } &
 71 |         while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done
 72 |         rm -f .BSnippetsHiddenFile
 73 |         echo "Success!"
 74 |         cd $repositoryName || { echo 'Update Failed'; exit 1; }
 75 |         git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit."
 76 |         chmod a+x install.sh #this might be necessary in your case but wasnt in mine.
 77 |         ./$nameOfInstallFile "update" || exit 1
 78 |         cd ..
 79 |         rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; }
 80 |       else
 81 |         exit 1
 82 |       fi
 83 |     else
 84 |       echo "$repositoryName is already the latest version"
 85 |     fi
 86 |   fi
 87 | }
 88 | 
 89 | getConfiguredPlayer()
 90 | {
 91 |   if [ ! -z "${YTVIEWPLAYER+x}" ]; then
 92 |     player="$YTVIEWPLAYER"
 93 |     return 0
 94 |   fi
 95 |   if [[ $(uname -s) == "Linux" ]]; then
 96 |     if command -v vlc &>/dev/null; then
 97 |       player="vlc"
 98 |     elif command -v mpv &>/dev/null; then
 99 |       player="mpv"
100 |     elif command -v mplayer &>/dev/null; then
101 |       player="mplayer"
102 |     else
103 |       echo "Error: no supported video player installed (vlc, mpv or mplayer)" >&2
104 |       return 1
105 |     fi
106 |   elif [[ $(uname -s) == "Darwin" ]]; then
107 |     if [[ -f /Applications/VLC.app/Contents/MacOS/VLC ]]; then
108 |       player="/Applications/VLC.app/Contents/MacOS/VLC"
109 |     elif [[ -f $HOME/Applications/VLC.app/Contents/MacOS/VLC ]]; then
110 |       player="$HOME/Applications/VLC.app/Contents/MacOS/VLC"
111 |     elif command -v mpv &>/dev/null; then
112 |       player="mpv"
113 |     elif [[ -f /Applications/mpv.app/Contents/MacOS/mpv ]]; then
114 |       player="/Applications/mpv.app/Contents/MacOS/mpv"
115 |     elif [[ -f $HOME/Applications/mpv.app/Contents/MacOS/mpv ]]; then
116 |       player="$HOME/Applications/mpv.app/Contents/MacOS/mpv"
117 |     else
118 | 	  if [[ $(mdutil -s / | grep "Indexing enabled." 2>/dev/null) != "" ]]; then
119 | 	    vlc_md=$(mdfind kMDItemCFBundleIdentifier = "org.videolan.vlc" 2>/dev/null)
120 | 	    if [[ $vlc_md != "" ]]; then
121 | 	      player="$vlc_md/Contents/MacOS/VLC"
122 | 	    else
123 | 	      mpv_md=$(mdfind kMDItemCFBundleIdentifier = "io.mpv" 2>/dev/null)
124 | 	      if [[ $mpv_md != "" ]]; then
125 | 	        player="$mpv_md/Contents/MacOS/mpv"
126 | 	      else
127 | 	        echo "Error: no supported video player installed (VLC or mpv)" >&2
128 | 	        return 1
129 | 	      fi
130 | 	    fi
131 | 	  else
132 | 	    echo "Error: no supported video player installed (VLC or mpv)" >&2
133 | 	    return 1
134 | 	  fi
135 |     fi
136 |   fi
137 | }
138 | 
139 | # Get the video titles
140 | channelview()
141 | {
142 |   mkdir -p "$HOME"/.cache/ytview/channels/"$channel" || return 1
143 |   httpGet "https://www.youtube.com/user/$channel/videos?hl=en" | grep "Duration" | awk '{print $10 " " $11 " " $12 " " $13 " " $14 " " $15 " " $16 " " $17 " " $18 " " $19 " " $20 " " $21 " " $22 " " $23 " " $24 " " $25 " " $26 " " $27 " " $29}' | sed 's/aria-describedby="description-id.*//' | sed s/title=// | sed 's/"//' | sed 's/"//' | awk '{printf "%s.\t%s\n",NR,$0}'  | sed  s/'&#39;'/"'"/g | sed s/'&amp;'/'and'/g | sed s/\&quot\;/\"/g > "$HOME"/.cache/ytview/channels/"$channel"/titles.txt || return 1
144 | 
145 |   # Get the video urls
146 |   httpGet "https://www.youtube.com/user/$channel/Videos?hl=en" | grep "watch?v=" | awk '{print $6}' | sed s/spf-link// | sed s/href=// | sed 's/"//' | sed 's/"//' | sed '/^\s*$/d' | sed 's/\//https:\/\/www.youtube.com\//' | awk '{printf "%s.\t%s\n",NR,$0}' > "$HOME"/.cache/ytview/channels/"$channel"/urls.txt || return 1
147 | 
148 |   # Print 20 first video titles for the user to choose from
149 |   head -n 20 "$HOME"/.cache/ytview/channels/"$channel"/titles.txt || return 1
150 |   # Prompt the user for video number
151 |   read -p "Choose a video: " titlenumber
152 |   if [[ -n ${titlenumber//[0-9]/} ]]; then
153 |     echo "Canceled." >&2
154 |     exit 0
155 |   fi
156 | 
157 |   # Play the video with your player
158 |   $player $(sed -n $(echo "$titlenumber")p < "$HOME"/.cache/ytview/channels/"$channel"/urls.txt | awk '{print $2}') > /dev/null 2>&1 &
159 | }
160 | 
161 | searchview()
162 | {
163 |   search=$(echo "$search" | tr " " + )
164 |   mkdir -p "$HOME"/.cache/ytview/searches/"$search"
165 | 
166 |   #Get video titles
167 |   httpGet "https://www.youtube.com/results?hl=en&search_query=$search" | grep "Duration" | grep "watch?v=" | awk '{print $13 " " $14 " " $15 " " $16 " " $17 " " $18 " " $19 " " $20 " " $21 " " $22 " " $23 " " $23}' | sed 's/aria-describedby="description-id.*//g' | sed s/title=// | sed 's/"//g' | sed s/spf-link// | sed 's/data-session-link=itct*.//' | sed s/spf-prefetch//g | sed 's/rel=//g' | sed 's/"//' | awk '{printf "%s.\t%s\n",NR,$0}' | sed  s/'&#39;'/"'"/g | sed  s/'&amp;'/'and'/g | sed s/\&quot\;/\"/g > "$HOME"/.cache/ytview/searches/"$search"/titles.txt || return 1
168 | 
169 |   #Get video urls
170 |   httpGet "https://www.youtube.com/results?hl=en&search_query=$search" | grep "watch?v=" | awk '{print $5}' | sed s/vve-check// | sed 's/href="/https:\/\/www.youtube.com/' | sed 's/"//' | sed s/class="yt-uix-tile-link"// | sed '/^\s*$/d' | awk '{printf "%s.\t%s\n",NR,$0}' > "$HOME"/.cache/ytview/searches/"$search"/urls.txt || return 1
171 |   #Print 20 first video titles for the user to choose from
172 |   cat "$HOME"/.cache/ytview/searches/"$search"/titles.txt || return 1
173 | 
174 |   #Let the user choose the video number
175 |   read -p "Choose a video: " titlenumber
176 |   if [[ -n ${titlenumber//[0-9]/} ]]; then
177 |     echo "Canceled." >&2
178 |     exit 0
179 |   fi
180 | 
181 |   #Play the video with your favorite player
182 |   $player $(sed -n $(echo "$titlenumber")p < "$HOME"/.cache/ytview/searches/"$search"/urls.txt | awk '{print $2}') > /dev/null 2>&1 &
183 | }
184 | 
185 | usage()
186 | {
187 |   cat <<EOF
188 | Ytview
189 | Description: Search and play youtube videos right from the terminal.
190 | Usage: ytview [flag] [string] or ytview [videoToSearch]
191 |   -s  Searches youtube
192 |   -c  Shows the latest videos of a channel
193 |   -u  Update Bash-Snippet Tools
194 |   -h  Show the help
195 |   -v  Get the tool version
196 | Examples:
197 |   ytview -s Family Guy Chicken Fight
198 |   ytview -c Numberphile
199 | EOF
200 | }
201 | 
202 | getConfiguredClient || exit 1
203 | 
204 | 
205 | while getopts "vuc:s:h*:" option; do
206 |   case "${option}" in
207 |     s) if [[ $flag != "channel" ]]; then
208 |          search=$(printf '%s ' "$@")
209 |          flag="search"
210 |        else
211 |          echo "Error: search and channel options are mutually exclusive" >&2
212 |          exit 1
213 |        fi
214 |         ;;
215 |     c) if [[ $flag != "search" ]]; then
216 |          channel="$OPTARG"
217 |          flag="channel"
218 |        else
219 |          echo "Error: search and channel options are mutually exclusive" >&2
220 |          exit 1
221 |        fi
222 |        ;;
223 |     h) usage && exit 0 ;;
224 |     u) checkInternet && update && exit 0 || exit 1;;
225 |     v) echo "Version $currentVersion" && exit 0 ;;
226 |     *) usage && exit 0 ;;
227 |   esac
228 | done
229 | 
230 | if [[ $# == "0" ]]; then
231 |   usage
232 |   exit 0
233 | elif [[ $1 == "help" ]]; then
234 |   usage
235 |   exit 0
236 | elif [[ $1 == "update" ]]; then
237 |   checkInternet || exit 1
238 |   update
239 |   exit 0
240 | elif [[ $flag == "search" ]]; then
241 |   checkInternet || exit 1
242 |   getConfiguredPlayer || exit 1
243 |   searchview || exit 1
244 | elif [[ $flag == "channel" ]]; then
245 |   checkInternet || exit 1
246 |   getConfiguredPlayer || exit 1
247 |   channelview || exit 1
248 | else
249 |   checkInternet || exit 1
250 |   search=$(printf '%s ' "$@")
251 |   getConfiguredPlayer || exit 1
252 |   searchview || exit 1
253 | fi
254 | 


--------------------------------------------------------------------------------
/ytview/ytview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexanderepstein/Bash-Snippets/581a6b4ea681005e3f8add37dbed74aaec65479f/ytview/ytview.png


--------------------------------------------------------------------------------